windows 如何让 for 循环使用逗号分隔的字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2112694/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I get a for loop to work with a comma delimited string?
提问by jcollum
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?
就是这样。我错过了什么?
回答by i_am_jorf
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).
tokens=1
意味着您只需要每行上的第一个标记。你想要线上的所有令牌。eol=,
表示您想将逗号解释为行尾注释的开始。你想用它delims=,
来表示逗号是分隔符(而不是空格的默认值)。
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:
FOR /F 主要用于对文件中的行进行操作。你不这样做。您在单个字符串上操作,因此鲁本斯的答案更接近您想要的:
@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.
这也有效,但可能不会以您想要的方式扩展。请注意,您必须使用 ^ 字符对字符串中的逗号进行转义,并且必须指定所需的标记,然后使用后续变量 %g、%h 和 %i 来获取它们。
回答by Rubens Farias
Try this:
尝试这个:
set test=1,2,3,4
for /d %%f IN (%test%) do echo %%f
回答by ghostdog74
@OP, and while you are learning how to use DOS batch scripting, you might want to learn vbscript (or powershell) as well. These are alternatives and they make your batch scripting easier, especially when it comes to more complex tasks.
@OP,在您学习如何使用 DOS 批处理脚本的同时,您可能还想学习 vbscript(或 powershell)。这些是替代方案,它们使您的批处理脚本更容易,尤其是在涉及更复杂的任务时。
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 the above as mysplit.vbs and on command line
将上述内容另存为 mysplit.vbs 并在命令行上
C:\test>cscript //nologo mysplit.vbs 1,2,3,4
1
2
3
4