How to escape / pass the % character to the Sub

34 Views Asked by At

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.

2

There are 2 best solutions below

2
jeb On BEST ANSWER

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

0
OJBakker On

You can not escape a % with a caret. You can escape a % by doubling it, so for % use a % to escape this character.