我怎样才能在文件中搜索这个或那个(2 件事)?

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)

  • 另见`grep $'then\nthere'`和`grep -e then -e there`。请注意,`\|` 在 BRE 中不是标准的。剩下的就是。Bash 仅在`"`、`$`、`\ `、`\`` 和换行符之前特别处理双引号内的反斜杠。 (3认同)

小智 7

只是一个快速的附录,大多数口味都有一个名为 egrep 的命令,它只是带 -E 的 grep。我个人更喜欢打字

egrep "i(Pod|Pad|Phone)" access.log
Run Code Online (Sandbox Code Playgroud)

比使用 grep -E