Linux 当 grep "\\" XXFile 我得到“尾随反斜杠”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20342464/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
When grep "\\" XXFile I got "Trailing Backslash"
提问by dong
Now I want to find whether there are lines containing '\' character. I tried grep "\\" XXFile
but it hints "Trailing Backslash". But when I tried grep '\\' XXFile
it is OK. Could anyone explain why the first case cannot run? Thanks.
现在我想查找是否有包含 '\' 字符的行。我试过了,grep "\\" XXFile
但它提示“尾随反斜杠”。但是当我尝试grep '\\' XXFile
它时就可以了。谁能解释为什么第一个案例不能运行?谢谢。
回答by John Kugelman
The difference is in how the shell treats the backslashes:
不同之处在于 shell 如何处理反斜杠:
When you write
"\\"
in double quotes, the shell interprets the backslash escape and ends up passing the string\
to grep. Grep then sees a backslash with no following character, so it emits a "trailing backslash" warning. If you want to use double quotes you need to apply two levels of escaping, one for the shell and one for grep. The result:"\\\\"
.When you write
'\\'
in single quotes, the shell does notdo any interpretation, which means grep receives the string\\
with both backslashes intact. Grep interprets this as an escaped backslash, so it searches the file for a literal backslash character.
当您用
"\\"
双引号书写时,shell 会解释反斜杠转义并最终将字符串传递\
给 grep。然后 Grep 看到一个没有跟随字符的反斜杠,因此它发出“尾随反斜杠”警告。如果要使用双引号,则需要应用两级转义,一级用于 shell,一级用于 grep。结果:"\\\\"
。当你写
'\\'
在单引号,外壳也没有做任何解释,grep的接收字符串该装置\\
与两个反斜杠完好。Grep 将此解释为转义的反斜杠,因此它会在文件中搜索文字反斜杠字符。
If that's not clear, we can use echo
to see exactly what the shell is doing. echo
doesn't do any backslash interpretation itself, so what it prints is what the shell passed to it.
如果这还不清楚,我们可以使用echo
来查看 shell 正在做什么。echo
本身不做任何反斜杠解释,所以它打印的是 shell 传递给它的内容。
$ echo "\"
\
$ echo '\'
\
回答by Nikolaos Kakouros
You could have written the command as
你可以把命令写成
grep "\\" ...
This has two pairs of backslashes which bash will convert to two single backslashes. This new pair will then be passed to grep as an escaped backslash getting you what you want.
这有两对反斜杠,bash 会将它们转换为两个单反斜杠。然后,这对新对将作为转义反斜杠传递给 grep,让您得到您想要的东西。