Mic*_*ant 55 grep regular-expression
我有一个包含“then”和“there”的文件。
我可以
$ grep "then " x.x
x and then some
x and then some
x and then some
x and then some
Run Code Online (Sandbox Code Playgroud)
我可以
$ grep "there " x.x
If there is no blob none some will be created
Run Code Online (Sandbox Code Playgroud)
如何在一次操作中同时搜索两者?我试过
$ grep (then|there) x.x
Run Code Online (Sandbox Code Playgroud)
-bash: 意外标记附近的语法错误`('
和
grep "(then|there)" x.x
durrantm.../code
# (Nothing)
Run Code Online (Sandbox Code Playgroud)
小智 76
您需要将表达式放在引号中。您收到的错误是 bash 将 解释(
为特殊字符的结果。
此外,您需要告诉 grep 使用扩展的正则表达式。
$ grep -E '(then|there)' x.x
Run Code Online (Sandbox Code Playgroud)
如果没有扩展正则表达式,你必须逃离|
,(
和)
。请注意,我们在这里使用单引号。Bash 特别对待双引号内的反斜杠。
$ grep '\(then\|there\)' x.x
Run Code Online (Sandbox Code Playgroud)
在这种情况下不需要分组。
$ grep 'then\|there' x.x
Run Code Online (Sandbox Code Playgroud)
像这样的事情是必要的:
$ grep 'the\(n\|re\)' x.x
Run Code Online (Sandbox Code Playgroud)
小智 7
只是一个快速的附录,大多数口味都有一个名为 egrep 的命令,它只是带 -E 的 grep。我个人更喜欢打字
egrep "i(Pod|Pad|Phone)" access.log
Run Code Online (Sandbox Code Playgroud)
比使用 grep -E
归档时间: |
|
查看次数: |
75706 次 |
最近记录: |