Search code examples
batch-filecmdspecial-charactersdelayedvariableexpansion

How to use delayedexpansion to handle value in batch script


I am facing issue with reading contents of CSV files in batch script. I have a series of files say My_A_File.csv, My_B_File.csv ... My_Z_File.csv. The issue I was facing is reading special characters in them. Hence, wanted to read the values with delayedexpansion turned off.

When I read the values in the block with disabledelayedexpansion, they are empty! How can I handle this?

Script:

@echo off
setlocal enabledelayedexpansion
for /L %%g in (65,1,90) do (
    cmd /c exit /b %%g
    set codeval=!=ExitCodeAscii!
    set fileToReadFrom=My_!codeval!_File.csv

    if exist My_!codeval!_File.csv (
        echo Outer-!fileToReadFrom!
        echo Outer-!codeval!
        setlocal disabledelayedexpansion
        echo Inner-%fileToReadFrom%
        echo Inner-%codeval%
        endlocal
    )
)

Output:

Outer-My_A_File.csv
Outer-A
Inner-
Inner-

Solution

  • This how the delayed expansion is supposed to work.However you can access the variables with CALL but this will the performance (mind that you cant CALL FOR ):

    @echo off
    setlocal enabledelayedexpansion
    for /L %%g in (65,1,90) do (
        cmd /c exit /b %%g
        set codeval=!=ExitCodeAscii!
        set fileToReadFrom=My_!codeval!_File.csv
    
        if exist My_!codeval!_File.csv (
            echo Outer-!fileToReadFrom!
            echo Outer-!codeval!
            setlocal disabledelayedexpansion
              call echo Inner-%%fileToReadFrom%%
              call echo Inner-%%codeval%%
            endlocal
        )
    )
    

    or you can use pipes.Which also will hit the performance (now you can use break|for "usebackq" %%a in ("Inner-%%fileToReadFrom%%") do @echo %%~a):

    @echo off
    setlocal enabledelayedexpansion
    for /L %%g in (65,1,90) do (
        cmd /c exit /b %%g
        set codeval=!=ExitCodeAscii!
        set fileToReadFrom=My_!codeval!_File.csv
    
        if exist My_!codeval!_File.csv (
            echo Outer-!fileToReadFrom!
            echo Outer-!codeval!
            setlocal disabledelayedexpansion
               break|echo Inner-%%fileToReadFrom%%
               break|echo Inner-%%codeval%%
            endlocal
        )
    )