dos batch iterate through a delimited string

The for command handles a number of delimiters by default. In this case you can do

@echo off

set servers=127.0.0.1,192.168.0.1,10.100.0.1

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

If you run into a delimiter that is not natively supported, you could do a replace to first prepare the string so it is in the right format

@echo off

set [email protected]@10.100.0.1
set servers=%servers:@=,%

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

Using recursive calls has the chance to run out of stack space once you go over a certain number of items in the list. Also testing it, the recursion pattern seems to run a bit slower.

Leave a Comment