如何让 for 循环使用逗号分隔的字符串? [英] How do I get a for loop to work with a comma delimited string?
问题描述
这是我目前的代码:
for/f "tokens=1 eol=," %%f IN ("1,2,3,4") do (回声.回声%%f)
我希望产生:
<预><代码>.1.2.等等……
但我得到:
<预><代码>.1就是这样.我错过了什么?
您误解了选项.
tokens=1
意味着您只需要每行的第一个标记.您需要在线上的所有令牌.eol=,
表示您想将逗号解释为行尾注释的开始.您想使用delims=,
来表示逗号是分隔符(而不是空格的默认值).
FOR/F 主要用于对文件中的行进行操作.你不这样做.您正在对单个字符串进行操作,因此鲁本斯的答案更接近您想要的:
@ECHO 关闭SET 测试=1,2,3,4FOR/D %%F IN (%test%) DO (回声.回声%%F)
但是,理论上,您应该可以这样说:
FOR/F "usebackq delims=, tokens=1-4" %%f IN ('1^,2^,3^,4') DO (回声.回声%%f回声.回声%%g回声.回声%%h回声.回声%%i)
这也有效,但可能无法按您想要的方式扩展.请注意,您必须使用 ^ 字符对字符串中的逗号进行转义,并且必须指定所需的标记,然后使用后续变量 %g、%h 和 %i 来获取它们.
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?
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 usedelims=,
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.
这篇关于如何让 for 循环使用逗号分隔的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!