代码之家  ›  专栏  ›  技术社区  ›  Nayana Adassuriya

嵌套for循环中用于启用DelayedExpansion的语法

  •  0
  • Nayana Adassuriya  · 技术社区  · 6 年前

    如果我简化了我的需求,我希望使用批处理文件得到这些字符串的最后两位数字。这不是确切的要求。但我让理解变得简单了。:)

     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]!:-= %) 不正确。关于如何在delayedxpansion内执行delayedxpansion并更正此语法的任何想法

    1 回复  |  直到 6 年前
        1
  •  1
  •   Squashman Stephan    6 年前

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

    @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