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
将其视为普通字符。
在将参数传递给程序之前,shell 首先展开所有转义序列,因此它将 解释\$
为转义序列并将单个参数传递$
给grep
,该参数与行尾匹配。由于每一行都有结尾,所以任何行都应该匹配:)