如果有人能帮助我满足这个请求我将不胜感激。
我需要一个动态批处理脚本来执行以下命令任意数量的文件:
Copy 1.txt + 2.txt + 3.txt + 4.txt newfile.txt
假如我有以下文件:
1.txt
2.txt
3.txt
...很快
我尝试了一下:Copy *.txt newfile.txt
合并时排序不正确。它实际上最终这样做:Copy 3.txt + 4.txt + 2.txt + 1.txt newfile.txt
另外,我需要它来使用复制命令而不是类型命令。
我找不到适当的方法来执行此操作,因为在线的大多数 FOR 循环示例都使用 TYPE,这并不适合我想要实现的目标。
非常感谢您的帮助!
答案1
我不相信这copy
会改变合并文件的排序顺序。然而,接下来自我解释脚本可以帮助:
@ECHO OFF
SETLOCAL EnableExtensions DisableDelayedExpansion
pushd d:\bat\files\folder
REM echo(&echo SHOW files to be merged in different sort order
REM erase newfile.txt 2>NUL
REM @ECHO ON
REM @for %%G in (
REM "/-C" "/O:N" "/O:S" "/O:E" "/O:D /T:C" "/O:D /T:W"
REM ) do dir %%~G *.txt|findstr "\.txt$"
REM @ECHO OFF
echo(&echo RESULT: copy *.txt newfile.txt
erase newfile.txt 2>NUL
rem (optional): to throw away trailing `Ctrl+Z`, use `/B` switch as follows:
rem copy /Y *.txt newfile.txt /B
@ECHO ON
copy /Y *.txt newfile.txt
findstr "^" *.txt
@ECHO OFF
echo(&echo(&echo RESULT: merge *.txt in defined order: change `/O` switch
echo(
type nul> newfile.txt
set /A "_files=0"
for /F "delims=" %%G in ('
dir /B /O:N *.txt
') do @if not "%%G"=="newfile.txt" (
echo(%%~G
set /A "_files+=1"
copy /Y newfile.txt + %%~G newfile.txt /B >NUL
)
echo %_files% file^(s^) merged.
rem (optional): to add trailing `Ctrl+Z`, remove `REM` in next line
REM copy newfile.txt + NUL newfile.txt >NUL
@ECHO ON
findstr "^" *.txt
@ECHO OFF
popd
请注意,如果取消注释(删除所有 7 个),则命令REM
后面的注释代码片段pushd
将显示要以不同排序顺序合并的文件REM
。我将其保留在这里是为了进行调试。
结果:
==> D:\bat\SU\1002948.bat
RESULT: copy *.txt newfile.txt
==> copy /Y *.txt newfile.txt
1.txt
2.txt
3.txt
4.txt
1 file(s) copied.
==> findstr "^" *.txt
1.txt:1111
2.txt:2
3.txt:333
4.txt:44
newfile.txt:1111
newfile.txt:2
newfile.txt:333
newfile.txt:44
newfile.txt:→
RESULT: merge *.txt in defined order: change `/O` switch
1.txt
2.txt
3.txt
4.txt
4 file(s) merged.
==> findstr "^" *.txt
1.txt:1111
2.txt:2
3.txt:333
4.txt:44
newfile.txt:1111
newfile.txt:2
newfile.txt:333
newfile.txt:44
==>
这里尾随的→
向右箭头符号newfile.txt
代表EOF
(文件结束,十六进制0x1A
),即Ctrl+ Z。