I am planning to write a batch script wherein I need to scan the values from a particular column of a CSV file one by one and store them in a variable for further processing.
Say, following is the CSV file:
A1 B1 C1 D1 E1 A2 B2 C2 D2 E2 A3 B3 C3 D3 E3 .. .. .. .. .. I have to read D1, execute a command using it's value, read D2, execute a command, and so on.
How can this be achieved?
4 Answers
Suppose you have a space-delimited file named yourfile.csv, and you want to read the fourth (D1) column, you should execute this:
for /F "tokens=4 delims= " %i in (yourfile.csv) do @echo %i 1On windows 7 with powershell you can easly parse the csv with Import-Csv EX:
Import-Csv -Delimiter " " -Header a,b,c,d,e c:\the.csv | foreach{ Write-Host $_.d } 1Here's a batch file I wrote up to dump a list of all my domain users (several thousand) into a file, one username per file (order not important). Since the "net group" command dumps the list of users in THREE columns (fixed width), I used the "token" syntax in the following batch file to do this.
@echo off REM * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * REM Turns three-column output from NET GROUP command into a REM single column of domain usernames REM * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * SET NGCSV=UserList3Col.csv SET NGCSVT1=UserList3Col.csv.temp1 SET NGCSVT2=UserList3Col.csv.temp2 SET NGFINAL=UserListFinal.txt setlocal EnableDelayedExpansion net group /domain "Domain Users" > %NGCSV% REM * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * REM Now strip out the crap REM ...make a temporary copy COPY %NGCSV% %NGCSVT2% REM ...strip off the crap using alternating temp files findstr /B /L /V /C:"The request" %NGCSVT2% > %NGCSVT1% findstr /B /L /V /C:"Group name" %NGCSVT1% > %NGCSVT2% findstr /B /L /V /C:"Comment" %NGCSVT2% > %NGCSVT1% findstr /B /L /V /C:"Members" %NGCSVT1% > %NGCSVT2% findstr /B /L /V /C:"-----" %NGCSVT2% > %NGCSVT1% findstr /B /L /V /C:"The command" %NGCSVT1% > %NGCSVT2% REM ...make the last temporary copy the final copy and clean up COPY %NGCSVT2% %NGCSV% DEL %NGCSVT1% DEL %NGCSVT2% REM * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * REM Now convert it all to one column del %NGFINAL% REM ...Column 1 for /F "tokens=1" %%A in (%NGCSV%) do @echo %%A >> %NGFINAL% REM ...Column 2 for /F "tokens=2" %%A in (%NGCSV%) do @echo %%A >> %NGFINAL% REM ...Column 3 for /F "tokens=3" %%A in (%NGCSV%) do @echo %%A >> %NGFINAL% (Note that "!" characters in usernames aren't handled by this batch file, but that didn't affect me.)
I also recommend using this article: ...to learn more about how delimiters are treated.
Check out the answers on this question... It's not exactly the same, but it goes over parsing a csv file in a batch script:
1