Escaping a quote in findstr search string

Merlyn Morgan-Graham picture Merlyn Morgan-Graham · Feb 13, 2011 · Viewed 17.5k times · Source

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.

Answer

Merlyn Morgan-Graham picture Merlyn Morgan-Graham · Feb 13, 2011

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