合并多个文本文件但跳过每个文件的第一行和最后一行
Merge multiple text files but skip first and last line of each file
我有一百个结构如下的文本文件:
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 }; )
...
文件名是随机的,class文件名也是随机的,但以"Category_"
开头
我知道如何将所有文件合并在一起:
@echo off
for /r %%i in (*.txt) do (
if not %%~nxi == output.txt (
copy /A output.txt+"%%i" && echo. >> output.txt
)
)
但不确定如何跳过每个文件的第一行和最后一行。能否请您提供一些帮助,谢谢。
这是一个工作代码示例
@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
以下是其功能的简要总结:
Setlocal
允许在 for-loop 中引用更新的变量值
- 删除现有
output
并重置 var
变量
For
每个文本文件,不是 output.txt
- 将
var
的值重置为空
For
此文本文件中的每一行,跳过第一行:
- 如果
var
不为空,echo
其值
Set
的值var
到当前的line
>>
将所有 echo
重定向到 output.txt
请注意,最后 2 个步骤的顺序允许您跳过最后一行,因为您总是重复上一行。
这意味着如果文件只有两行,它不会回显任何东西,
如果有3行只会回显中间那一行,
如果它有 4 行,它将回显中间的两行,依此类推
我有一百个结构如下的文本文件:
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 }; )
...
文件名是随机的,class文件名也是随机的,但以"Category_"
开头我知道如何将所有文件合并在一起:
@echo off
for /r %%i in (*.txt) do (
if not %%~nxi == output.txt (
copy /A output.txt+"%%i" && echo. >> output.txt
)
)
但不确定如何跳过每个文件的第一行和最后一行。能否请您提供一些帮助,谢谢。
这是一个工作代码示例
@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
以下是其功能的简要总结:
Setlocal
允许在 for-loop 中引用更新的变量值
- 删除现有
output
并重置var
变量 For
每个文本文件,不是output.txt
- 将
var
的值重置为空 For
此文本文件中的每一行,跳过第一行:- 如果
var
不为空,echo
其值 Set
的值var
到当前的line
- 将
>>
将所有 echo
重定向到 output.txt
请注意,最后 2 个步骤的顺序允许您跳过最后一行,因为您总是重复上一行。
这意味着如果文件只有两行,它不会回显任何东西,
如果有3行只会回显中间那一行,
如果它有 4 行,它将回显中间的两行,依此类推