windowsbatch-filecmdescapingfindstr

How to escape / pass the % character to the Sub


I have this batch file, where I am trying to extract a substring but in the end result the % character is being removed. Eg some%value becomes somevalue. I have escaped the & character but nothing works for the percent character.

setlocal enabledelayedexpansion

For /F "Delims=" %%A In ('FindStr /I "<start>.*</end>" "AllApiLogs.log"') Do (
    Call :Sub "%%A"
)
GoTo :EOF

:Sub
Set "Line=%~1"
Set "Line=%Line:&amp;=^&%"
Set "Up2Sub=%Line:*<start>=%"
Set "SubStr=%Up2Sub:</end>="&:"%"
Echo '%SubStr%', >> ApiRegExExtract.log
Exit /B

How do I work around this? Is there a way to escape all characters that need escaping in batch files? I am new to these.


Solution

  • In your case, you lose the percent sign by using Call :Sub "%%A".

    Just change that to:

    For /F "Delims=" %%A In ('FindStr /I "<start>.*</end>" "AllApiLogs.log"') Do (
        set "line=%%A"
        Call :Sub
    )
    GoTo :EOF
    
    :Sub
    
    Set "Line=%Line:&amp;=^&%"
    ...
    

    It's an effect of the CALL command, it parses the arguments two times