批处理 - 用于循环参数顺序

时间:2017-03-31 11:33:03

标签: batch-file for-loop cmd

我试图在for循环中使用令牌来分隔我的批处理文件中的CSV文件。这是代码片段:

for /f "tokens=1-31* delims=," %%a in ("!revamped!") do (
  echo %%a
  echo %%b
  ...
  echo %%y
  echo %%z
      rem what parameter should I use next?
)

使用%%a一直到%%z后,我不知道接下来应该使用哪个参数。

问题%%a循环中使用所有%%zfor之后使用参数的顺序是什么?< / p>

1 个答案:

答案 0 :(得分:2)

正如其他人已经在评论中指出的那样,for /F仅限于31个令牌。有以下解决方法:

  1. 使用嵌套的for /F循环,如下所示(此处使用50个令牌):

    for /F "tokens=1-25* delims=," %%A in ("!revamped!") do (
        for /F "tokens=1-25* delims=," %%a in ("%%Z") do (
            echo token # 01: "%%A"
            echo token # 25: "%%Y"
            echo token # 26: "%%a"
            echo token # 50: "%%y"
            echo remaining tokens: "%%z"
        )
    )
    
  2. 使用标准for loop循环获得几乎无限数量的令牌:

    for /F "tokens=*" %%A in ("!revamped!") do (
        set /A "INDEX=0" & rem // (reset index number)
        set "LINE=%%A"
        rem /* In the following, every delimiter `,` is replaced by `" "`;
        rem    the entire line string is enclosed within `""`; hence
        rem    the result is a list of space-sepatated quoted tokens,
        rem    which can easily be handled by a standard `for` loop;
        rem    the surrounding quotes are later removed by the `~` modifier;
        rem    regard that the line string must not contain `*` or `?`: */
        for %%a in ("!LINE:,=" "!") do (
            set /A "INDEX+=1" & rem // (build index just for demonstration)
            echo token # !INDEX!: "%%~a"
        )
    )