Search code examples
batch-filefor-loopescapingfindstr

BATCH: Escaping


Im trying to make simple batch file that would copy all lines with width="10 string from .htm file to .txt but im stuck with doublequote " symbol in the string

My code:

for /F "tokens=*" %%g in ('FINDSTR /C:"width=\"10" "htmfile.htm"') do (echo %%g >> test.txt)


'FINDSTR /C:"width=' this is still working but when I add the ", its not working anymore. I added escaping \" and and also tryed ^" but it is still not working.


I would be glad for any help.


Solution

  • You need to first ensure that the cmd.exe parser sends the correct match string to FindStr, i.e. /C:"width=\"". To do that I'd suggest escaping the closing doublequote with the standard escape character, the caret, ^.

    I don't really see the purpose of the For loop, (unless you're just trying to remove any leading whitespace):

    @Echo Off
    FindStr /C:"width=\"10^" "htmfile.htm" 2>Nul >"test.txt"
    Pause
    

    Because the content of the For parentheses are ran through another cmd.exe instance you'd need to escape the caret escape character with two more carets:

    @Echo Off
    For /F "Tokens=*" %%A In ('FindStr /C:"width=\"10^^^" "htmfile.htm" 2^>Nul'
    ) Do (Echo %%A)>>"test.txt"
    Pause