Search code examples
windowsbatch-file

Removing double quote inside a Windows batch FOR loop variable


I have the following Windows batch file:

@setlocal enableDelayedExpansion

@set TEXT="ABC" "DEF"
@set AGE_GROUP_LIST="[20, 30)" "[30, 40)"

@for %%A in (%AGE_GROUP_LIST%) do @(
@set TEXT=!TEXT:"=!
@echo !TEXT!

@set A=!!A:"=!
@echo      %%A
)

@endlocal

When I ran it, it outputs:

ABC DEF
     "[20, 30)"
ABC DEF
     "[30, 40)"

However I want it to output where the double quote is removed for FOR loop's variable. How would I write it so that it does.

ABC DEF
     [20, 30)
ABC DEF
     [30, 40)

Solution

  • %%A and !A! are completely unrelated variables, which is why nothing is happening in your code. %%A is a token that only exists for the duration of the for loop, and you can't set it like a regular variable.

    What you can do, however, is use the ~ substitution modifier like this:

    echo      %%~A
    

    The tilde says to remove any surrounding quotes; you can see other substitution modifiers in the output of for /?.

    It's also worth noting that you don't need to put an @ at the beginning of each line if you just have @echo off as the first line of your script.