Home > Enterprise >  BAT file to read many .txt files in the folder and merge them into .csv file and add part of the fil
BAT file to read many .txt files in the folder and merge them into .csv file and add part of the fil

Time:04-20

I want my code to read every .txt file and add the first 6 numbers of the file name to the front of the line... I have the first part of the code set up and I know how the second part needs to look I just don`t know how to merge them..

@echooff
del Build_count.csv
for /f %%a in ('dir /b *.txt') do for /f "tokens=*" %%b in (%%a) do echo %%a,%%b >> Build_count.csv

@echo off
setlocal enabledelayedexpansion
if exist List.cvs del List.cvs
for %%a in (*.txt) do (
    set fn=%%~na
    set fn=!fn:~0,6!
  )

CodePudding user response:

Just appending one code to the other doesn't help you. You need to insert the second snippet into the first loop:

@echo off
setlocal enabledelayedexpansion
(for /f %%a in ('dir /b *.txt') do (
  set "fn=%%~na"
  for /f "tokens=*" %%b in (%%a) do (
    echo !fn:~0,6!,%%b 
  )
))>Build_count.csv

For every matching file extract the desired string, then in another loop read every line and write the string plus the line. Redirect the whole thing to the destination file in one go (that's much faster than opening the file, finding the end, adding a line and closing the file again for each and every line). Deleting it beforehand isn't necessary, because the code overwrites the file anyway.

Note: the for /f loop as it stands now ignores empty lines and lines starting with a ;. Adaptions are necessary if that's a problem.

  • Related