Help in writing a batch script to parse CSV file and output a text file Help in writing a batch script to parse CSV file and output a text file windows windows

Help in writing a batch script to parse CSV file and output a text file


@ECHO OFFIF "%~1"=="" GOTO :EOFSET "filename=%~1"SET fcount=0SET linenum=0FOR /F "usebackq tokens=1-10 delims=," %%a IN ("%filename%") DO ^CALL :process "%%a" "%%b" "%%c" "%%d" "%%e" "%%f" "%%g" "%%h" "%%i" "%%j"GOTO :EOF:trimSET "tmp=%~1":trimleadIF NOT "%tmp:~0,1%"==" " GOTO :EOFSET "tmp=%tmp:~1%"GOTO trimlead:processSET /A linenum+=1IF "%linenum%"=="1" GOTO picknamesSET ind=0:displayIF "%fcount%"=="%ind%" (ECHO.&GOTO :EOF)SET /A ind+=1CALL :trim %1SETLOCAL ENABLEDELAYEDEXPANSIONECHO !f%ind%!!tmp!ENDLOCALSHIFTGOTO display:picknamesIF %1=="" GOTO :EOFCALL :trim %1SET /a fcount+=1SET "f%fcount%=%tmp%"SHIFTGOTO picknames

This batch scipt:

  • accepts one parameter, the name of the file to process;

  • does not verify the presence of : at the end of a header token, and when the values are displayed they are placed immediately after the corresponding header tokens;

  • trims all the leading spaces (but not the trailing ones);

  • considers the first row to be the header row, which also defines the number of tokens to process in subsequent rows;

  • supports up to 10 tokens, and the two areas highlighted in bold italics are responsible for that (so when you need to change the maximum number, modify both areas: if you increase the number, you must expand the "%%a" "%%b" "%%c" … list, and, likewise, if you decrease the number, then shrink the list).


I know this is an old question, but this type of question is my favorite one so here it is my answer:

@echo offsetlocal EnableDelayedExpansionrem Create heading array:set /P headingRow=< %1set i=0for %%h in (%headingRow%) do (    set /A i+=1    set heading[!i!]=%%~h)rem Process the file:call :ProcessFile < %1exit /B:ProcessFileset /P line=:nextLine    set line=:EOF    set /P line=    if "!line!" == ":EOF" goto :EOF    set i=0    for %%e in (%line%) do (        set /A i+=1        for %%i in (!i!) do echo !heading[%%i]!%%~e    )goto nextLineexit /B

This program have not any limit in the number of fields. This version requires to enclose in quotes the elements that may have spaces or other Batch delimiters, but this restriction may be easily fixed.


Python makes this so easy it should be regulated by the government.

from csv import DictReaderwith open('file', 'rb') as file:    reader = DictReader(file)    for line in reader:        for field in reader.fieldnames:            print '{0}{1}'.format(field.strip(), line[field].strip())         print '\n'

Edit: I guess you need something native to the Windows command shell. Oh well.