嵌套for循环中EnableDelayedExpansion的语法

时间:2018-05-21 02:58:19

标签: batch-file cmd

如果我简化了我的要求,我想使用批处理文件获取这些字符串的最后两位数字。这不是确切的要求。但我理解起来很简单。 :)

 11-22-33
 11-22-44
 11-22-55
 11-22-66

预期结果

33
44
55
66

这是我写的代码

 @echo off
    SetLocal EnableDelayedExpansion

    REM Fill strings to a array
    set DIR_COUNT=0
    for %%x in ("11-22-33" "11-22-44" "11-22-55" "11-22-66") do (    
        set /A DIR_COUNT+=1
        set  CONTENT_DIR_NAME=%%~x
        set "DIR_LIST[!DIR_COUNT!]=!CONTENT_DIR_NAME!"
    )

    REM This part is working when I hard code the index of array to 1. I placed this two lines for testing purpose of above code.
    for %%a in (%DIR_LIST[1]:-= %) do set mfgName=%%a
    echo %mfgName%

    REM this loop doesn't work because the syntax not correct. 
    for /L %%i in (1,1,%DIR_COUNT%) do (    
        for %%a in (%!DIR_LIST[%%i]!:-= %) do (
            set mfgName=%%a
            echo !mfgName!
        )
    )

由于我理解(%!DIR_LIST[%%i]!:-= %)的语法不正确。任何想法如何在DelayedExpansion中延迟扩展并更正此语法

1 个答案:

答案 0 :(得分:1)

以下是批处理文件的正确语法。

@echo off
SetLocal EnableDelayedExpansion

REM Fill strings to a array
set DIR_COUNT=0
for %%x in ("11-22-33" "11-22-44" "11-22-55" "11-22-66") do (    
    set /A DIR_COUNT+=1
    set CONTENT_DIR_NAME=%%~x
    set "DIR_LIST[!DIR_COUNT!]=!CONTENT_DIR_NAME!"
)

for /L %%i in (1,1,%DIR_COUNT%) do (    
    for %%a in (!DIR_LIST[%%i]:-^= !) do (
        set mfgName=%%a
        echo !mfgName!
    )
)
pause