Search code examples
for-loopbatch-filecmdsplit

Run command for each line of variable in cmd


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?


Solution

  • 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