如何批量访问列表?

时间:2018-11-27 18:46:44

标签: batch-file

我有两个字符串:

jobID: w,x,y,z
Test: A,B,C,D

我正在迭代第二个字符串(用逗号分隔后),并打印该生成列表的值和第一个字符串中的值。

到目前为止,我的代码是这样:

@echo off
setlocal EnableDelayedExpansion

set num=-1
for %%a in ("%jobID:,=" "%") do (
   set /A num+=1
   set elem[!num!]=%%a
)

set i=-1
for %%a in ("%Test:,=" "%") do (
   set /A i=i+1
   echo file name is %%a and first list element is !%elem[!%i%!]%!
)

我期望的是:

file name is A and first list element is w
file name is B and first list element is x
file name is C and first list element is y
file name is D and first list element is z

我得到的是

file name is "A" and first list element is "0"
file name is "B" and first list element is "1"
file name is "C" and first list element is "2"
file name is "D" and first list element is "3"

编辑:我需要获取不带双引号的值。

1 个答案:

答案 0 :(得分:5)

本质上,您需要获得两个阶段的变量扩展。这是通过使用CALL命令来完成的。

将echo命令更改为此。

call echo file name is %%a and first list element is %%elem[!i!]%%

这一切都在Arrays, linked lists and other data structures in cmd.exe (batch) script

中进行了解释

使用命令修饰符将变量从FOR中删除,这些修饰符在FOR命令的帮助文件的最后部分中进行了说明。

You can now use the following optional syntax:

    %~I         - expands %I removing any surrounding quotes (")
    %~fI        - expands %I to a fully qualified path name
    %~dI        - expands %I to a drive letter only
    %~pI        - expands %I to a path only
    %~nI        - expands %I to a file name only
    %~xI        - expands %I to a file extension only
    %~sI        - expanded path contains short names only
    %~aI        - expands %I to file attributes of file
    %~tI        - expands %I to date/time of file
    %~zI        - expands %I to size of file
    %~$PATH:I   - searches the directories listed in the PATH
                   environment variable and expands %I to the
                   fully qualified name of the first one found.
                   If the environment variable name is not
                   defined or the file is not found by the
                   search, then this modifier expands to the
                   empty string

The modifiers can be combined to get compound results:

    %~dpI       - expands %I to a drive letter and path only
    %~nxI       - expands %I to a file name and extension only
    %~fsI       - expands %I to a full path name with short names only
    %~dp$PATH:I - searches the directories listed in the PATH
                   environment variable for %I and expands to the
                   drive letter and path of the first one found.
    %~ftzaI     - expands %I to a DIR like output line