batch-filereplaceenvironment-variablesfindstr

Escape percent when replacing text in an environment variable in a batch file


Without going into why, I need a batch file which extracts a set of section names from an INI file. Luckily all the section names I want begin with the same string, so piece of cake, right?. The problem is the section name may include "%20". For example, this INI file:

[Testing\Test%20x]
A=aaa
B=bbb

Unfortunately, findstr replaces the %20 with 0. Here's what I've come up with for my batch file:

@ECHO off
SETLOCAL
FOR /F "delims=" %%A IN ('findstr \[Testing* Test.ini') DO (CALL :DOIT %%A)
ENDLOCAL
GOTO :EXIT
:DOIT 
SET First=%1
SET Second=%First:[=%
SET Third=%Second:]=%
SET Fourth=%Third:0=20%
SET Fifth=%Fourth:20=%%20%
ECHO %1 %First% %Second% %Third% %Fourth% %Fifth%
EXIT /B

:EXIT

Which produces the output:

[Testing\Test0x] [Testing\Test0x] Testing\Test0x] Testing\Test0x Testing\Test20x Testing\Testx0

Escaping the percent with a backslash or caret doesn't work. How can I get the percent sign into the string?


Solution

  • @ECHO OFF
    SETLOCAL
    
    SET "sourcedir=u:\your files"
    SET "filename1=%sourcedir%\q77476155.txt"
    
    FOR /f "delims=" %%b IN ('findstr \[Testing* "%filename1%"') DO SET "string=%%b"&CALL :showme
    
    GOTO :EOF
    
    :showme
    ECHO %string%
    GOTO :eof
    

    I used a file named q77476155.txt containing your data for my testing.

    It isn't findstr that's doing the substitution, it's %2 appearing in the parameter to the subroutine that's being replaced.

    Now - what is it that you want to do with thw string?