Home > Blockchain >  Merge multiple txt in several subdirectories into 1 txt for each subdirectories in Windows
Merge multiple txt in several subdirectories into 1 txt for each subdirectories in Windows

Time:01-14

OS : Windows 10

Here are example directory structure.

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

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

I want to merge txt file for each folder like this.

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)

@echo off

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

I tried this batch but the result is not my expected.

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

Please help me how to proceed on the task. Thank you.

CodePudding user response:

Use 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"
        )
    )
)

Instead of type to write the result file, copy can be used also:

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"
    )
)

The *.txt files are merged in alphabetical order due to the /O:N of the dir command.

  •  Tags:  
  • Related