How do I escape a double quote with GNU grep for windows/dos?

谁说胖子不能爱 提交于 2019-12-07 01:02:59

问题


I'm trying to search for

Assembly="Foobar

in all files and direct the output to tmp.txt

I've tried (cmd/error)

grep -r "Assembly=\"Foobar" . >> tmp.txt error (invalid argument)

grep -r "Assembly=""Foobar" . >> tmp.txt
error (not enough space)

grep -r 'Assembly="Foobar' . >> tmp.txt
error (not enough space)

very frustrating. Any suggestions?


回答1:


You need to worry about escaping quotes for both grep and cmd.exe

grep expects quotes to be escaped as \"

cmd.exe escapes quotes as ^". The quote is a state machine, meaning unescaped quotes toggle quote semantics on and off. When quoting is on, special characters like <, |, &, etc are treated as literals. The first unescaped quote turns on quote semantics. The next quote turns quote semantics off. It is only possible to escape a quote when quoting is OFF. Unbalanced quotes result in the remainder being quoted. So in your case, the >>tmp.txt is not treated as redirection by cmd.exe, so it gets passed to grep as an argument.

Any of the following will work:

grep -r "Assembly=\"Foobar^" . >>tmp.txt
grep -r ^"Assembly=\"Foobar" . >>tmp.txt
grep -r ^"Assembly=\^"Foobar^" . >>tmp.txt
grep -r Assembly=\^"Foobar . >>tmp.txt

If your search term included spaces, then grep needs the enclosing quotes, so you would need any of the first three forms. The last form would not work with spaces in the search term.



来源:https://stackoverflow.com/questions/19815531/how-do-i-escape-a-double-quote-with-gnu-grep-for-windows-dos

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