7

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?

3 Answers 3

16

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.

Sign up to request clarification or add additional context in comments.

2 Comments

This is the most close to what I want. The only disadvantage is that I don't know in advance the number of tokens - it is user input. I guess it can be fixed by choosing some value equals to maximum tokens list size such as "tokens=1-10".
@ks1322 You could also use the linefeed technic
5

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
)

3 Comments

@Ed, I want to iterate string, delimited by whitespaces, so I guess quoting is necessary
@Alvin, Joey - did you try my example? (Although you're right, /D is unnecessary)
@ks1322 - quoting isn't necessary in batch scripts - space is the default delimiter (hence why you have to quote file system paths containing spaces)
2

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
)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.