Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escaping a quote in findstr search string

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.

like image 618
Merlyn Morgan-Graham Avatar asked Feb 13 '11 06:02

Merlyn Morgan-Graham


2 Answers

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"/>
like image 159
Ciove Avatar answered Sep 21 '22 15:09

Ciove


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
like image 28
Merlyn Morgan-Graham Avatar answered Sep 23 '22 15:09

Merlyn Morgan-Graham