Batch Script: Concatenating multiple files in multiple folders into one file

batchshell-scriptwindows

I have about 20 folders and all of them have around 100 csv files each. I want to combine all of them together into one file. How should I do this? I know about copy command to combine files of one folder. If I do that, I get 20 files in 20 folders. To combine them, how will I traverse in each folder and do ?

I am trying to write a batch script like this:

FOR /D /R %G in ("*") DO (
cd %G 
COPY *.csv new.csv )

But, it is not working correctly. Any suggestions?

Best Answer

If all of the files really are valid CSV, then amending the last line to loop over the files in the current folder using variable %H, change the copy to:

TYPE %H >>new.csv

Should work (not fully tested I'm afraid).

However, a better approach would be to use PowerShell since that has cmdlets to handle CSV input and output and so it would be able to handle any oddities in the structure of the files without corrupting the output.

Related Question