Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate string in cmd for loop?

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?

like image 492
ks1322 Avatar asked Jun 22 '12 09:06

ks1322


People also ask

How do I run a loop in CMD?

Related commands:FOR /R - Loop through files (recurse subfolders) . FOR /D - Loop through several folders. FOR /L - Loop through a range of numbers. FOR /F - Loop through items in a text file.

What is %% A?

%%a are special variables created by the for command to represent the current loop item or a token of a current line. for is probably about the most complicated and powerful part of batch files. If you need loop, then in most cases for has you covered.

What is %% f in Batch Script?

%%parameter A replaceable parameter: in a batch file use %%G (on the command line %G) FOR /F processing of a text file consists of reading the file, one line of text at a time and then breaking the line up into individual items of data called 'tokens'.

How do I loop a text file in a batch file?

Reading of files in a Batch Script is done via using the FOR loop command to go through each line which is defined in the file that needs to be read. Since there is a no direct command to read text from a file into a variable, the 'for' loop needs to be used to serve this purpose.


1 Answers

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.

like image 162
jeb Avatar answered Oct 16 '22 15:10

jeb