Missing “!” string when EnableDelayedExpansion

半世苍凉 提交于 2019-12-24 13:01:56

问题


When I enabled DelayedExpansion in the script, it doesn't echo out the "!" string in the file name. For instance:

Original
File01-TEXT!.txt

Echo out
File01-TEXT.txt

I guess it's because of the setlocal EnableDelayedExpansion, but I can't remove because I need it.

@echo off
setlocal EnableDelayedExpansion

cd "C:\Files"
for %%a in (*.txt) do (

    REM Here's the problem...
    echo %%a

    set "str=%%a"
    set new_str=!str:0,3!
)

echo %new_string%

pause >nul

回答1:


Depending on the real code, you can work with delayed expansion disabled, enable it where access to modified content is needed and then disable again

@echo off
    setlocal enableextensions disabledelayedexpansion

    cd "C:\Files"
    for %%a in (*.txt) do (
        set "str=%%a"

        rem Option 1 
        echo file: %%a
        setlocal enabledelayedexpansion
        echo substring: !str:~0,3!
        endlocal 

        rem Option 2 - capture changed value to use inside non delayed expansion context
        setlocal enabledelayedexpansion
        for %%b in ("!str:~0,3!") do (
            enlocal
            echo %%a -- %%~b
        )
    )


来源:https://stackoverflow.com/questions/33257824/missing-string-when-enabledelayedexpansion

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!