1

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.

Vaibhav Garg
  • 3,630
  • 3
  • 33
  • 55

2 Answers2

1

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

OJBakker
  • 602
  • 1
  • 5
  • 6
1

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

jeb
  • 78,592
  • 17
  • 171
  • 225
  • That worked. Thank you. Are there any other characters I need to take care off? – Vaibhav Garg May 27 '23 at 15:00
  • Bullet proof replacing with batch is a bit tricky. Even [reading a file](https://stackoverflow.com/a/4531090/463115) line by line is tricky enough – jeb May 27 '23 at 16:13