我想尝试一下grep使用正则表达式的命令,发现它们的行为与我的预期不同。例如,考虑temp具有以下内容的文件
helloworld
hello_world
hello world
hello how are you world
hello wor ld
hello_*_..world
helloEworld
Run Code Online (Sandbox Code Playgroud)
当我跑步时
grep 'hello.*world' temp
Run Code Online (Sandbox Code Playgroud)
它返回
helloworld
hello_world
hello world
hello how are you world
hello_*_..world
helloEworld
Run Code Online (Sandbox Code Playgroud)
正如预期的那样。但当我跑步时
grep 'hello.+world' temp
Run Code Online (Sandbox Code Playgroud)
它什么也不返回...虽然当我\之前添加时+
grep 'hello.\+world' temp
Run Code Online (Sandbox Code Playgroud)
它返回正确的输出
hello_world
hello world
hello how are you world
hello_*_..world
helloEworld
Run Code Online (Sandbox Code Playgroud)
在上一个命令中添加\ before并运行*
grep 'hello.\*world' temp
Run Code Online (Sandbox Code Playgroud)
什么也没返回...
为什么grep 'hello.+world' temp如果没有 则该命令不起作用\?
为什么它恰恰相反*?
我应该什么时候使用\?
GNU 支持多种类型的正则表达式grep:
基本正则表达式 (BRE) - 默认值。不直接支持+,但支持*. 当你逃避它时,你就会变得+有意义\\+。来自GNU grep 文档:
In basic regular expressions the meta-characters \xe2\x80\x98?\xe2\x80\x99, \xe2\x80\x98+\xe2\x80\x99, \xe2\x80\x98{\xe2\x80\x99, \xe2\x80\x98|\xe2\x80\x99,\n\xe2\x80\x98(\xe2\x80\x99, and \xe2\x80\x98)\xe2\x80\x99 lose their special meaning; instead use the backslashed\nversions \xe2\x80\x98\\?\xe2\x80\x99, \xe2\x80\x98\\+\xe2\x80\x99, \xe2\x80\x98\\{\xe2\x80\x99, \xe2\x80\x98\\|\xe2\x80\x99, \xe2\x80\x98\\(\xe2\x80\x99, and \xe2\x80\x98\\)\xe2\x80\x99.\nRun Code Online (Sandbox Code Playgroud)扩展正则表达式 (ERE) - 该选项-E可以实现此目的。既支持+又*直接支持。
-P选项启用 PCRE。支持类似于 Perl 的语法,例如向前查找和向后查找。BRE 和 ERE 通常是POSIX 定义的标准类,因此您应该在任何grep渴望 POSIX 兼容性的类上找到它们,并期望具有类似的行为。