将多个子目录中的多个txt合并为Windows中每个子目录1个txt

Merge multiple txt in several subdirectories into 1 txt for each subdirectories in Windows

OS : Windows 10

以下是示例目录结构。

D:\Fruits\Apple\ a.txt k.txt c.txt

D:\Fruits\Mango\ g.txt q.txt b.txt

我想像这样为每个文件夹合并 txt 文件。

D:\Fruits\Apple\ a.txt k.txt c.txt merge.txt (a+k+c)

D:\Fruits\Mango\ g.txt q.txt b.txt merge.txt (g+q+b)

@回声关闭

for /r " D:\Fruits" %%a in (*.txt) do type "%%a" >>"merge.txt"

我尝试了这批,但结果不是我的预期。

D:\Fruits\merge.txt (a+k+c+g+q+b)

请帮助我如何继续执行任务。谢谢。

使用for /D to loop through the directories, then process each of them individually, using dir to retrieve all *.txt files, findstr to exclude the result file merge.txt and for /F to iterate through the files. To eventually write merge.txt, use output redirection >:

for /D %%J in ("D:\Fruits\*") do (
    > "%%~J\merge.txt" (
        for /F "delims= eol=|" %%I in ('
            dir /B /A:-D-H-S /O:N "%%~J\*.txt" ^| findstr /V /I /C:"merge.txt"
        ') do (
            type "%%~J\%%I"
        )
    )
)

代替type to write the result file, copy也可以使用:

for /D %%J in ("D:\Fruits\*") do (
    > "%%~J\merge.txt" rem/ // deplete the file in advance;
    for /F "delims= eol=|" %%I in ('
        dir /B /A:-D-H-S /O:N "%%~J\*.txt" ^| findstr /V /I /C:"merge.txt"
    ') do (
        copy /B "%%~J\merge.txt" + "%%~J\%%I" "%%~J\merge.txt"
    )
)

由于 dir 命令的 /O:N*.txt 文件按字母顺序合并。