Say you’ve got a Windows command to run over and over with a different arg each time. Wouldn’t it be nice if you could make a word list and loop over it the way bash does?
Because Cmd is RetardedTM, the FOR loop it offers is only for line-oriented records. Imagine a spreadsheet. Records are like rows, and fields are like cells.
FOR has delimiters to chop up a record into fields (aka tokens) and each gets its own letter of the alphabet. The problem there is you need to anticipate the number of fields you’ll need (capped at 26), your loop will only run once (useless for a list), and all the words will become variables simultaneously (awful).
@ECHO OFF
FOR /F "tokens=1-4 delims= " %%i IN ("Hermes Zapp Leela Amy") DO (
ECHO *%%i*
ECHO *%%j*
ECHO *%%k*
ECHO *%%l*
)
A double-quoted string, however intuitive, isn’t gonna work. FOR can loop over the stdout from a command though (single quotes). We’ll just have to feed the loop multiple lines then (as mentioned in an earlier post)…
Chaining echoes works, but it’s tedious and ugly, even for batch code.
@ECHO OFF
FOR /F "delims=" %%i IN ('ECHO Hermes^&ECHO Zapp^&ECHO Leela^&ECHO Amy') DO (
ECHO *%%i*
)
Finally, the tidy equivalent…
@ECHO OFF
SET LIST=Hermes,Zapp,Leela,Amy,Zoidberg,Fry,BenderSET LIST=ECHO %LIST:,=^^^&ECHO %
FOR /F "delims=" %%i IN ('%LIST%') DO (
ECHO *%%i*
)
A new trick is introduced here. Batch can do some limited string manipulation on the contents of variables (the %blah% kind, not the %1 or %i kind). In this case, each comma is getting replaced with “^&ECHO “. The carets get interpreted away immediately on that line, then again when FOR first looks at it.
If the list gets long, you can break it up into several concatenations.
SET LIST=Hermes,Zapp,Leela,Amy,Zoidberg,Fry,Bender
SET LIST=%LIST%,Professor,Kif
Tags: Windows