Home > other >  Run command for each line of variable in cmd
Run command for each line of variable in cmd

Time:09-17

I want to run a command (in this example echo) for each line of a variable (in cmd, i.e. batch). In this case, the lines are supposed to be separated by \n, but others delimiters should work as well.

Therefore I set a variable:

> set var="foo\nbar"

I then want to run my command (echo) on each line, i.e. on "foo" and "bar". I tried to use for for this:

> for /f "tokens=* delims=\n" %s in (%var%) do (echo %s)
foo\nbar

Obviously this isn't what I wanted - I expected something like

foo
bar

How do I achieve this?

CodePudding user response:

You can use a real line feed character to get your desired effect.

setlocal EnableDelayedExpansion
(set \n=^
%=empty, do not modify this line=%
)

set "var=foo!\n!bar"

for /f "delims=" %%L in ("!var!") do (
  echo ## %%L
)

Other delimiters in the variable
can be used, but have to be replaced later with a linefeed.

setlocal EnableDelayedExpansion
(set \n=^
%=empty, do not modify this line=%
)

set "var=my,list,delimited,by,commas"

for %%L in ("!\n!")  do (
  for /f "delims=" %%k in ("!var:,=%%~L!") do (
    echo ## %%k
  )
)

About the delims option in FOR /F

The delims option is for splitting a line into tokens, that will not create more loop iterations - NEVER.

FOR /F "tokens=1,2,3 delims=;" %%A in ("123;456;789") do echo ... %%A, %%B, %%C

Output

... 123, 456, 789

not

... 123
... 456
... 789

CodePudding user response:

%var% is used as the input set to FOR-parcer. But before running FOR command we should replace \n with space ( outer quotes):

Syntax: %variable:StrToFind=NewStr%

Theese spaces become delimiters in our FOR-parser.

To remove quotes automatically from a a single letter variable use symbol ~

Syntax: %~1

So we have next code:

set var="foo\nbar"
for %%A IN (%var:\n=" "%) DO @ECHO=%%~A

P.S. As jeb truly said the code won't work correctly with special symbols: *, ?, %% in variable content.

  • Related