我如何获得一个for循环用逗号分隔的字符串工作? [英] How do I get a for loop to work with a comma delimited string?

查看:159
本文介绍了我如何获得一个for循环用逗号分隔的字符串工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的code迄今:

This is my code so far:

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

我期待的产生:

.
1
.
2
.

等等......

etc...

而是我得到:

.
1

就是这样。我在想什么?

And that's it. What am I missing?

推荐答案

您已经误解的选项。


  • 标记= 1 意味着你只需要在每一行的第一个标记。你要全部上线的标记。

  • EOL =,意味着你要跨preT逗号作为年初的行注释结束的。要使用 delims =,而不是指示逗号分隔符(而不是空白的默认值)。

  • 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主要用于对文件中的流水线作业。你没有这样做。你在一个字符串操作,所以鲁本斯的回答是更接近你想要什么:

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
)

本作品为好,但可能不会在扩展自己想要的方式。请注意,您必须使用逃脱^字符字符串中的逗号,你必须指定你想要的标记,然后用随后的变量%G,%H和%我得到他们。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆