1

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
Community
  • 1
  • 1
WhatWhereWhen
  • 473
  • 1
  • 5
  • 6

1 Answers1

3

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
        )
    )
MC ND
  • 69,615
  • 8
  • 84
  • 126
  • Works well ! But what does `enableextensions` do here? – WhatWhereWhen Oct 21 '15 at 11:58
  • 1
    @WhatWhereWhen, Just an habit. Usually, by default, extensions are enabled and you can do substring operations in variables. But sometimes extensions are disabled and code fails. Y automatically type `setlocal enableextensions [disable/enable]delayedexpansion` almost without thinking. Unless there is a reason not to do it, I prefer to explicitly indicate what the code waits. – MC ND Oct 21 '15 at 12:16
  • @Squashman, AGGG! I should be blind. My fault, thank you. Once corrected, time to repeat a hundred times *"I should not copy/paste"* – MC ND Oct 21 '15 at 12:32