Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Windows batch FOR command tab delimiter

I'm trying to use the Windows batch FOR command.

How do I specify a TAB character as a delimiter? The default is space and tab, but I want tab only.

I've tried this, but it doesn't work:

FOR /F "tokens=3 delims=^T" %i in (test.txt) do @echo %i

It seems to be splitting on the T character instead of a tab. I've also tried a literal pasted into the command prompt, but I get a syntax error.

like image 666
jterrace Avatar asked Dec 03 '22 01:12

jterrace


2 Answers

You need a literal tab character in the quoted options string. The literal TAB works both in a batch file and on the command line.

If you are attempting to type a TAB into the command line, then file name completion may be thwarting your efforts. You can disable name completion by using CMD /F:OFF. You will then be able to enter a literal TAB character.

You can also run into problems trying to enter a TAB into a batch script depending on the text editor that you use. Some programmer's editors have settings that automatically convert TABs into spaces. You will need to make sure your editor is not doing that.

So you just need to change your "tokens=3 delims=^T" string to use a TAB literal instead of ^T

like image 178
dbenham Avatar answered Dec 26 '22 13:12

dbenham


Ngaaa.. talk about an afternoon headache...

I had the same problem today... I needed to parse lines with FOR /F where each line was a number of sentences (each with embedded spaces, maybe) with each sentence delimited by TABs.

My problem is that my company coding standards (even for BATCH files) prohibits actual TAB characters from being in the source code (our editors prohibit putting TABs in, and our Version ctrl tools disallow any CheckIn of any text file with TABs or WTR [white-to-the-right].)

So, this is a hack, but it works on XP (hangs head... deep shame...)

SET REG_CPU="HKLM\Hardware\Description\System\CentralProcessor\0"
REG.EXE QUERY %REG_CPU% /V IDENTIFIER | FIND "REG_SZ" > RegCPUid.Tmp
for /F "tokens=2 delims=rR" %%i in (RegCPUid.Tmp) do SET TAB=%%~i

This works on XP but I havent checked Win7 or Win7[WoW64].

The temporary contents of RegCPUid.Tmp is ONE LINE, which looks like

"    IDENTIFIER<tab>REG_SZ<tab>x86 Family 6 Model 37 Stepping 2"    

The FOR command simply plucks out the lonely TAB between the two "R"s of IDENTIFIER and REG_SZ and sets the environment variable TAB to it.

Then my script can do all the FOR /F looping it wants with ONLY the tab character as a delimiter (and NOT a space) by...

for /F "tokens=1-3* delims=%TAB%" %%i in (Sentences.txt) do ECHO The THIRD sentence is %%k

All of this allows me to NOT have any hardcoded TAB characters in the BATCH file.

-dave

like image 20
djb Avatar answered Dec 26 '22 13:12

djb