This is in continuation with the question here. Batch Script: Concatenating multiple files in multiple folders into one file

I have 20 files with name 'new.csv' in 20 folders in the same parent directory. I want to concatenate all of them into one file. So, I want to do it in two steps.

  1. I am using XCOPY to copy each new.csv of each folder to new1, new2, new3 etc. in the parent folder. If I can do this, in my parent folder, I have 20 csvs, new1, new2..new20.csv.

  2. Then, I can just do a copy new*.csv final.csv. So, this is the code that I wrote to make the copies of each of these new.csv from each folder in the parent folder.

    setlocal EnableDelayedExpansion
    set /a i=0
    FOR /D /R %%G in ("*") DO (
    cd %%G 
    set  /a i=i+1
    XCOPY new.csv ..\new%!i!%.csv )

The problem is in creating a new file. I want to create 20 files with names, new1.csv, new2.csv, new3.csv...new20.csv. The counter value is getting incremented, but I cannot append it to 'new'. Could you please help.

  • I know you've self-answered, but your question makes no sense. First you say you have 20 files all named new.csv that you want to concatenate into one file. Next you say you want to create 20 files with names new1.csv, new2.csv... This is clearly contradictory. Which of the two are you trying to achieve? – Karan Jun 11 '15 at 6:52
  • I am sorry if it was unclear. I have tried to explain it. – pnv Jun 11 '15 at 6:58
  • Ok, got it. For the record you don't need this 2-step process but if you've got it working already that's good. – Karan Jun 11 '15 at 6:59
  • I knew it. Could you please share the easier method. – pnv Jun 11 '15 at 7:04

Thanks! I am answering myself, with whatever worked for me. I replaced the last line like this.

 XCOPY new.csv ..\new_!i!.csv 

If you want the full paths to the individual CSVs listed inside the consolidated CSV, use this:

for /r %f in (*.csv) do @echo "%f" >> New.csv && echo. >> New.csv && type "%f" >> New.csv && echo. >> New.csv && echo --- >> New.csv

If you just want the CSV contents, use this:

for /r %f in (*.csv) do @type "%f" >> New.csv && echo. >> New.csv

echo. adds a newline to the file and can be removed if not required to further shorten the command.

These commands have to be typed in the parent directory. If you're using them in a batch file just remember to double each % sign.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.