JSI Tip 8563. How can I process lines from a Tab Separated Value file in a batch script?

Jerold Schulman

October 11, 2004

1 Min Read
ITPro Today logo in a gray background | ITPro Today


If you use a FOR command to read the lines of a Tab Separated Value file, as in:

FOR /F "Tokens=*" %%a in (FILENAME) do ( set line=%%a call :DoSomeThing)   ORFOR /F "Tokens=*" %%a in ('type FILENAME') do ( set line=%%a call :DoSomeThing)

There is no way to parse the line variable for TAB characters using standard commands.

I have scripted RepTab.bat to replace each occurrence of a TAB character in a variable string with a character of your choosing.

The syntax for using RepTab.bat is:

CALL RepTab StringVar RepVar

Where StringVar is the name of the variable that contains one or more TAB characters, and RepVar is the name of a variable that contains the TAB replacement character.

NOTE: You should use a character that is not on the keyboard, such as (ALT+0171 on the Numeric Keypad).

Example:

If you know that the Tab Separate Value file has 5 columns:

set tabFOR /F "Tokens=*" %%a in ('type c:zipnewRepTab.log') do ( set line=%%a call :DoSomeThing ). . .. . .. . .goto  ...:DoSomeThingcall RepTab line tabFOR /F "Tokens=1-4* Delims" %%i in ('@echo %line%') do ( set col1=%%i set col2=%%j set col3=%%k set col4=%%l set col5=%%m)

RepTab.bat contains:

@echo offif {%2}=={} @echo Syntax RepTab StringVar FndVar&goto :EOFif exist "%TEMP%RepTab.VBS" goto doit@echo dim oString, objArgument>"%TEMP%RepTab.VBS"@echo Set objArgument = Wscript.Arguments>>"%TEMP%RepTab.VBS"@echo P2 = objArgument(1)>>"%TEMP%RepTab.VBS"@echo oString = Replace(objArgument(0), vbtab, P2)>>"%TEMP%RepTab.VBS"@echo Wscript.echo "*:" ^& oString>>"%TEMP%RepTab.VBS":doitfor /f "Tokens=1* Delims=:" %%a in ('call cscript //NOLOGO "%TEMP%RepTab.VBS" "%%%1%%" "%%%2%%"') do ( set %1=%%b)



Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like