batch-filedelayedvariableexpansion

Missing "!" string when EnableDelayedExpansion


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

Solution

  • 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 (
                endlocal
                echo %%a -- %%~b
            )
        )