Question : batch file to combine text files and append file name on each line into target file

I have a couple dozen csv files that I need copied into a single csv file. Easily done with a "copy \sourcedir\*.csv name.csv". However there's a catch. Each file contains a list of information unique to the server it was generated from the tool I'm using, but no reference to the server itself in the file. I need to add the filename to each copied line in the new csv file for easy manipulation in excel.

servername1.csv
servername2.csv
servername3.csv (etc)

I need a batch file that will add the file name to each line copied into the new csv file.
servername1.csv,data1,data2,etc
servername1.csv.data1,data2, etc
servername2.csv.data1,data2, etc
servername2.csv.data1,data2, etc
servername2.csv.data1,data2, etc
servername3.csv.data1,data2, etc

Right now my small amount of files is a couple dozen but this is something I will have to do with several hundred files on a regular basis. Some kind of loop that will go through the source folder and repeat this for every file in it. Thank you.

Answer : batch file to combine text files and append file name on each line into target file

Paste the script below into a text file with .cmd extension.  Customize the value of the folder variable on line 4 with the location of the folder containing the files.  Customize the value of the output variable on line 6 with the location of the consolidated file to create.  Running the script will create the output file.

Note that this will choke on special characters such as ampersands.  It's generally better to use vbscript for text manipulation.

1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
@echo off
setlocal
 
set folder=c:\sourcedir
set mask=*.csv
set output=output.csv
 
for /f "tokens=*" %%G in ('dir "%folder%\%mask%" /a:-d /b') do (
 for /f "tokens=*" %%H in ('type "%folder%\%%G"') do (
  echo %%G,%%H >> "%output%"
 )
)
Random Solutions  
 
programming4us programming4us