当grep的" \\\\" XXFile我"尾部的反斜杠"

问题描述:

现在我想找到是否有含\\字符线条。我试图的grep\\\\XXFile ,但它提示斜杠。但是,当我试图的grep'\\\\'XXFile 这是确定。任何人都可以解释为什么第一种情况下不能运行?谢谢你。

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.

所不同的是在外壳如何处理反斜杠:

The difference is in how the shell treats the backslashes:


  • 当你写在双引号\\\\,外壳间$ P $点反斜杠逃逸并最终传递字符串 \\ 来的grep。 grep的然后看见没有后面的字符一个反斜杠,所以它发出一个斜杠的警告。如果你想使用双引号,你需要使用转义的两个层次,一个是外壳和一个grep的。其结果是:\\\\\\\\

  • 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: "\\\\".

当你写'\\\\'在单引号,外壳做的的做任何除pretation,这指的grep接收字符串 \\\\ 与两个反斜杠完好。 grep的跨$ P $点这是一个转义反斜杠,因此它搜索文字反斜杠字符的文件。

When you write '\\' in single quotes, the shell does not do 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.

如果这是不明确的,我们可以使用回声来看看到底是什么壳做。 回声不做任何反斜线间pretation本身,所以它打印是shell传递什么吧。

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 "\\"
\
$ echo '\\'
\\