How to iterate string in cmd for loop?

15,676

Solution 1

That's because FOR/F splits a each line into multiple tokens, but you need to define how many tokens you want to process.

set var="1 2 3"

for /F "tokens=1-3" %%i in (%var%) do (  
  echo %%i
  echo %%j
  echo %%k
)

EDIT: Other solutions

Like the answer of Ed harper:
You could also use a normal FOR-loop, with the limitation that it will also try to serach for files on the disk, and it have problems with * and ?.

set var=1 2 3

for %%i in (%var%) do  (
    echo %%i
)

Or you use linefeed technic with the FOR/F loop, replacing your delim-character with a linefeed.

setlocal EnableDelayedExpansion
set LF=^


set "var=1 2 3 4 5"
set "var=%var: =!LF!%"
for /F %%i in ("!var!") do (  
  echo %%i
)

This works as the FOR/F sees five lines splitted by a linefeed instead of only one line.

Solution 2

Try FOR in place of FOR /F. Also, quoting the value when setting var is unnecessary:

set var=1 2 3

for %%i in (%var%) do  (
echo %%i
)

Solution 3

Because FOR /F loops every line of a text file, and when used with a string ("" quoted) it only do things on that line. It does delimit by whitespace, but that is to be used with the option tokens.

You should use FOR

set var=1 2 3

for %%i in (%var) do (
  echo %%i
)

If you want to loop numbers, use the following:

for /L %%i in (1,1,3) do (
  echo %%i
)
Share:
15,676
ks1322
Author by

ks1322

Apparently, this user prefers to keep an air of mystery about them.

Updated on June 26, 2022

Comments

  • ks1322
    ks1322 almost 2 years

    I am trying to iterate a string in batch script:

    set var="1 2 3"
    
    for /F %%i in (%var%) do (  
      echo %%i
    )
    

    and getting this output:

    C:\>batch.bat
    
    
    C:\>set var="1 2 3"
    
    C:\>for /F %i in ("1 2 3") do (echo %i )
    
    C:\>(echo 1 )
    1
    

    I expect that all 3 numbers will be printed:

    1
    2
    3
    

    What am I doing wrong?