合并多个文本文件,但跳过每个文件的第一行和最后一行

时间:2018-01-28 05:10:50

标签: batch-file batch-processing

我有一百个具有以下结构的文本文件:

file1.txt
Class Categeory_1 {
   (content 1, may contain many other block ending with }; )
};

file2.txt
Class Categeory_2 {
   (content 2, may contain many other block ending with }; )
};

我想合并所有文件而没有每个文件的第一行和最后一行,所以output.txt应该是:

(content 1, may contain many other block ending with }; )
(content 2, may contain many other block ending with }; )
...

文件名是随机的,类名也是随机的,但以"类别_"

开头

我知道如何将所有文件合并在一起:

@echo off
    for /r %%i in (*.txt) do (
        if not %%~nxi == output.txt (
            copy /A output.txt+"%%i" && echo. >> output.txt
        )
    )

但不确定如何跳过每个文件的第一行和最后一行。能否请你提供帮助,谢谢。

1 个答案:

答案 0 :(得分:0)

这是一个有效的代码示例

@echo off
setlocal enabledelayedexpansion

if exist output.txt del output.txt
set "var="
for /r %%i in (*.txt) do (
  if "%%~nxi" NEQ "output.txt" (
  set "var="
  for /f "usebackq skip=1 delims=" %%b in ("%%~i") do (
    if "!var!" NEQ "" Echo !var!
    set var=%%b
))) >> output.txt

以下是它的作用的快速摘要:

  1. Setlocal允许在for-loop
  2. 中引用更新的变量值
  3. 删除现有的output并重置var变量
  4. For每个文本文件,都不是output.txt
    1. var的值重置为空
    2. For此文本文件中的每一行,跳过第一行:
    3. 如果var不为空,则echo为其值
    4. Set var对当前line
    5. 的值
  5. >>将所有echo重定向到output.txt

    注意,最后两步的顺序是允许你跳过最后一行的顺序,因为你总是回显上一行。

    • 这意味着如果文件只有2行,则不会回显任何内容,

    • 如果它有3行,它只会回显中间的一行,

    • 如果它有4条线,它将回显中间的两条,等等。

相关问题