I saw this piece of code on a website that was a spin off of a previous stack overflow thread, however it is exactly what I'm trying to do utilizing batch. I have worked very little with batch and while it looks like it should produce the desired end result it's not doing quite what I would like, any and all help would be greatly appreciated. underneath the code I put an example of what I'm trying to accomplish.
@echo off
set local EnableDelayedExpansion
for %%f in (*.txt) do (
set i=0
for /F "delims=" %%l in (%%f) do (
set /A i+=1
set line!i!=%%l
)
echo %%f, !line1!, !line2!, !line3!, >> result.csv
text file 1 text file 2 text file 3 >> output.csv
1111, 2222, 3333 1111,2222,3333
1111, 2222, 3333 1111,2222,3333
1111, 2222, 3333 1111,2222,3333
1111, 2222, 3333 1111,2222,3333
You would need to change the settings of
sourcedir
anddestdir
to suit your circumstances.I used files named
q42500455*.txt
containing your data for my testing.Produces the file defined as %outfile%
The first
for
loop simply numbers each line from each of the files in the list and outputs the result to the temporary file (the name of which is irrelevant). The result is a file containingThe next
for
loop simply calculates the maximum line number used, tokenising the line number as%%a
by using:
as a delimiter.The next section counts the line number into
%%L
, then builds theline
from the matching line number in the tempfile. Since the tempfile contains line n in the order of file-specified, picking each line n and stringing them together will build the line as specified.Note that I doubt your data as posted, which has terminal
,
on each line except for the last file. I believe that this,
is missing and the procedure is expected to insert the,
s as separators.If this is so, then the changes required are:
to insert the comma, then
echo
all of the line bar the first character.This method performs a direct merge file by file, adjusting lines when one file have less lines than the others.