Question

How can I properly escape a quote in a search string when using findstr.exe?

Example:

findstr /misc:"namespace=\"" *.cs > ns.txt

This outputs to the console, instead of to the file I specified.

I am doing this directly on the command line, not actually in a batch file, though that information might be useful too.

Was it helpful?

Solution

Please correct me if I'm wrong, but I think I've figured it out:

findstr.exe /misc:^"namespace=\^"^" *.cs > ns.txt

This seems to give the correct output, even if you have spaces in your search string. It allows file redirection, piping, and additional literals in the same findstr.exe invocation to work correctly.

The original command in my question doesn't work because both cmd.exe and findstr.exe have special processing for the " character. I ended up with an unmatched set of quotes in cmd.exe's processing.

The new command in my answer works because ^" allows the quote to pass from cmd.exe to findstr.exe, and \" tells findstr.exe to ignore that quote for command processing purposes, and treat it as a character literal.

Edit:

Well, my solution was right, but the reason it is correct was totally wrong. I wrote a small program to test it.

I found out that cmd.exe passes this input to the program when I pass the bad command line:

test.exe /misc:namespace=" *.cs > ns.txt

With the characters escaped correctly, cmd.exe passes this input to the program (and redirects output to a file):

test.exe /misc:namespace=" *.cs

OTHER TIPS

Found Re: FINDSTR search for a couble quote and redirect/pipe the output

Try this: 

findstr > x.txt /S /I /M /C:"\.\"" * 

I have no idea why this works.

Doesn't work for piping the output though. See the related link piping findstr's output

According to my tests the correct escape character is backslash:

c:\Temp>findstr /isc:"session id=\"59620\"" C:\Temp\logs\some*.xml
C:\Temp\logs\some_2016_11_03.xml: <session id="59620" remoteAddress="192.168.195.3:49885"/>

Wouldn't this be just enough:

findstr /misc:namespace=^" *.cs > ns.txt

?

EDIT

If you were searching for a way to pass the " character inside a quoted parameter, then it could be (using your example)

findstr /misc:"namespace=""" *.cs > ns.txt

(the " character is repeated twice inside a quoted string).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top