Skip navigation

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


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
)

   OR

FOR /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 tab=«
FOR /F "Tokens=*" %%a in ('type c:\zipnew\RepTab.log') do (
 set line=%%a
 call :DoSomeThing 
)
. . .
. . .
. . .
goto  ...
:DoSomeThing
call RepTab line tab
FOR /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 off
if \{%2\}==\{\} @echo Syntax RepTab StringVar FndVar&goto :EOF
if 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"
:doit
for /f "Tokens=1* Delims=:" %%a in ('call cscript //NOLOGO "%TEMP%\RepTab.VBS" "%%%1%%" "%%%2%%"') do (
 set %1=%%b
)



Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish