Search code examples
csvbatch-filerecursionheader

batch - modify each csv files in subfolders


I try to make a batch script which update header line of each .csv file in folder (and subfolders). Since I don't want to really modify source files, I create new files with new headers, same content and new extension ".csv.modified"

The script works fine when I have only one .csv (I just remove the /s) but ignore content of other files when > 1.

Note: I have many subfolders and some of them contains whitespaces.

Any idea ?

@echo off
cls

setlocal enabledelayedexpansion 
set HEADERS=header1,header2  

for /f "delims=" %%i in ('dir /b /s *.csv') do (
    set filename=%%~i
    echo !filename!
    echo.

    set cpt=1
    set new_filename=!filename!.modified

    @copy nul "!new_filename!"
    echo creating !new_filename!
    echo %HEADERS%>"!new_filename!"

    for /f %%a in (%%~i) do (
        set line=%%a
        if !cpt! gtr 2 ( 
            echo Y
            echo !line!>>"!new_filename!" 
        ) else ( 
            echo N 
        )

        echo !cpt! %%a
        set /a cpt=!cpt!+1
    )

)

endlocal 

Solution

  • This should be all you need to achieve that:

    @SET "HEADERS=header1,header2"
    @FOR /F "DELIMS=" %%A IN ('DIR/B/S/A-D-S-L *.csv') DO @((ECHO %HEADERS%
        MORE +1 "%%~A")>"%%~A.modified")