How to get a for loop to work with a comma delimited string?

This is my code:

for /f "tokens=1 eol=," %%f IN ("1,2,3,4") do ( echo . echo %%f ) 

I expect to create:

 . 1 . 2 . 

etc.

But instead, I get:

 . 1 

What is it. What am I missing?

+6
windows cmd batch-file
source share
3 answers

You misunderstood the options.

  • tokens=1 means that you only need the first token on each line. You need all the tokens on the line.
  • eol=, means you want to interpret the comma as the beginning of the end of line comment. You want to use delims=, instead, to indicate that the comma is a delimiter (instead of the default value for spaces).

FOR / F is primarily intended to work in lines in a file. You do not do this. You work on one line, so Rubens answer is closer to what you want:

 @ECHO OFF SET test=1,2,3,4 FOR /D %%F IN (%test%) DO ( ECHO . ECHO %%F ) 

However, theoretically you should be able to say something like:

 FOR /F "usebackq delims=, tokens=1-4" %%f IN ('1^,2^,3^,4') DO ( ECHO . ECHO %%f ECHO . ECHO %%g ECHO . ECHO %%h ECHO . ECHO %%i ) 

This works as well, but probably does not scale the way you want. Note that you need to escape the comma in the string with the ^ character, and you must specify the desired markers, and then use the subsequent variables% g,% h and% i to get them.

+11
source share

Try the following:

 set test=1,2,3,4 for /d %%f IN (%test%) do echo %%f 
+1
source share

@OP, and while you are learning to use DOS batch scripts, you may need to learn vbscript (or powershell). These are alternatives, and they make your batch scripting easier, especially when it comes to more complex tasks.

 Set objFS=CreateObject("Scripting.FileSystemObject") Set objArgs = WScript.Arguments strInput = objArgs(0) s = Split(strInput,",") For Each i In s WScript.Echo i Next 

save above as mysplit.vbs and in command line

 C:\test>cscript //nologo mysplit.vbs 1,2,3,4 1 2 3 4 
0
source share

All Articles