Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
538 views
in Technique[技术] by (71.8m points)

windows - How do I get a for loop to work with a comma delimited string?

This is my code so far:

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

I'm expecting that to produce:

.
1
.
2
.

etc...

But instead I get:

.
1

And that's it. What am I missing?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You've misunderstood the options.

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

FOR /F is primarily for operating on lines in a file. You're not doing that. You're operating on a single string, 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, in theory, 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 doesn't scale in the way you want. Note that you have to escape the comma in the string using the ^ character, and you have to specify the tokens you want and then use the subsequent variables %g, %h and %i to get them.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...