Escaping a quote in findstr search string

我与影子孤独终老i 提交于 2020-01-01 04:51:06

问题


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.


回答1:


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



回答2:


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




回答3:


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"/>



回答4:


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).



来源:https://stackoverflow.com/questions/4982802/escaping-a-quote-in-findstr-search-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!