Batch file for loops

From Tutorials

Jump to: navigation, search

Loop through each environment var and value

 for /f "tokens=1* delims==" %%i in ('set') do (
    echo Name: %%i
    echo Value: %%j
 )
  • The set command will list all env vars
  • delims== specifies to split each line by '=' characters
  • tokens=1* specifies that the first section will be put into %%i, the * makes it so everything after the first section is put into %%j.
  • The contents of %%j are not the remaining collection of sections, but rather the rest of the raw string. i.e. foo=bar=bat=baz is really name: foo value: bar=bat=baz not value: barbatbaz.

Loop through an unknown amount of comma separated values in a string

Lets say you have a string that contains an unknown amount of values, but you do know the delimiter

 set BasketFullOfFruit=apple,orange,grape,lemon,apple,pineapple,banana,pear,banana,lemon,orange
 
 for %%i in (%BasketFullOfFruit%) do (
   echo %%i
 )
  • The for command has some built in delimiters already. Comma is one of them, so this above operation is easy.

If the delimiter is not one of the built in ones, we can do a replace operation first.

 set BasketFullOfFruit=apple[x]orange[x]grape[x]lemon[x]apple[x]pineapple[x]banana[x]pear[x]banana[x]lemon[x]orange
 
 set BasketFullOfFruit=%BasketFullOfFruit:[x]=,%
 
 for %%i in (%BasketFullOfFruit%) do (
   echo %%i
 )
  • We simply replace our delimiter '[x]' with ',' and then route it through the for loop.

Another, more complicated, slower and flawed approach is to use recursion. This pattern below works until you hit the stack limit. I'm putting it here as an example of what not to do !!

 set BasketFullOfFruit=apple]orange]grape]lemon]apple]pineapple]banana]pear]banana]lemon]orange
 
 call :FruitFinder "%BasketFullOfFruit%"
 goto :EOF
 
 :FruitFinder
   set FruitList=%1
   set FruitList=%FruitList:"=%
   for /f "tokens=1* delims=]" %%a IN ("%FruitList%") DO (
     if "%%a" NEQ "" echo %%a
     if "%%b" NEQ "" call :FruitFinder "%%b"
   )
   goto :EOF

  • To see this above script blow up, add a large amount of items in the BasketFullOfFruit. With enough items you'll run into a similar message
 ******  B A T C H   R E C U R S I O N  exceeds STACK limits ******
 Recursion Count=345, Stack Usage=90 percent
 ******       B A T C H   PROCESSING IS   A B O R T E D      ******
Personal tools