grep 是如何解释 \$ 的?

Hap*_*tal 13 unix grep regex command-line syntax

当我写

$ grep \$  
Run Code Online (Sandbox Code Playgroud)

然后我在终端上输入的任何内容都会匹配并打印在终端上。是如何\$解读的?

小智 18

所述外壳被解释\$并使其通过以作为grep的$,行字符的结束。所以假设你的行有一个结束,它会匹配:-)

如果要匹配$grep中的实际值,请使用以下选项之一:

grep \\\$
grep '\$'
Run Code Online (Sandbox Code Playgroud)

在前者中,shell解释\\\\$作为$,给人\$。在后者中,它根本不解释它。


至于你为什么要\$匹配美元符号而不是两个字符的序列的问题,正则表达式就像那些用于grep某些目的的特殊字符。其中一些是:

$       end of line
^       start of line
.       any character
+       1 or more of the preceeding pattern
*       0 or more of the preceeding pattern
{n,m}   between n and m of the preceeding pattern
[x-y]   any character between x and y (such as [0-9] for a digit).
Run Code Online (Sandbox Code Playgroud)

与许多其他人一起。

当您想匹配通常被视为特殊字符的 literla 字符时,您需要对其进行转义,以便grep将其视为普通字符。


Nic*_*yer 5

在将参数传递给程序之前,shell 首先展开所有转义序列,因此它将 解释\$为转义序列并将单个参数传递$grep,该参数与行尾匹配。由于每一行都有结尾,所以任何行都应该匹配:)

  • @Happy Mithal:见`man grep`;已经决定 `$` 匹配行尾,无论行是否被 `\n`、`\r`、两者或完全不同的东西分隔。一般情况下,正则表达式可用于匹配任何字符串,而不仅仅是“行”,而`$`用于匹配字符串的末尾。 (2认同)