与另一个命令一起使用时如何 grep 多个字符串?

Nie*_*man 12 linux grep bash pipe

我正在尝试找出如何使用:

grep -i
Run Code Online (Sandbox Code Playgroud)

在另一个命令上使用 grep 后,使用多个字符串。例如:

last | grep -i abc
last | grep -i uyx
Run Code Online (Sandbox Code Playgroud)

我希望将上述内容合并为一个命令,但是在互联网上搜索时,我只能找到有关如何在 grep 中使用多个字符串的参考,当 grep 与文件而不是命令一起使用时。我尝试过这样的事情:

last | grep -i (abc|uyx)
Run Code Online (Sandbox Code Playgroud)

或者

last | grep -i 'abc|uyx'
Run Code Online (Sandbox Code Playgroud)

但这是行不通的。获得我期望的结果的正确语法是什么?

提前致谢。

Sté*_*las 19

许多选项grep单独使用,从标准选项开始:

\n
grep -i -e abc -e uyx\ngrep -i 'abc\nuyx'\ngrep -i -E 'abc|uyx'\n
Run Code Online (Sandbox Code Playgroud)\n

通过一些grep实现,您还可以执行以下操作:

\n
grep -i -P 'abc|uyx' # perl-like regexps, sometimes also with\n                     # --perl-regexp or -X perl\ngrep -i -X 'abc|uyx' # augmented regexps (with ast-open grep) also with\n                     # --augmented-regexp\ngrep -i -K 'abc|uyx' # ksh regexps (with ast-open grep) also with\n                     # --ksh-regexp\ngrep -i 'abc\\|uyx'   # with the \\| extension to basic regexps supported by\n                     # some grep implementations. BREs are the\n                     # default but with some grep implementations, you\n                     # can make it explicit with -G, --basic-regexp or\n                     # -X basic\n
Run Code Online (Sandbox Code Playgroud)\n

您可以在周围添加(...)s abc|uyx\\(...\\)对于 BRE),但这不是必需的。s()s 等|也需要加引号才能按字面传递,grep因为它们是 shell 语言语法中的特殊字符。

\n

不区分大小写的匹配也可以作为正则表达式语法的一部分启用,并具有某些grep实现(非标准)。

\n
grep -P '(?i)abc|uyx' # wherever -P / --perl-regexp / -X perl is supported\ngrep -K '~(i)abc|uyx' # ast-open grep only\ngrep -E '(?i)abc|uyx' # ast-open grep only\ngrep '\\(?i\\)abc|uyx'  # ast-open grep only which makes it non-POSIX-compliant\n
Run Code Online (Sandbox Code Playgroud)\n

与标准选项相比,这些并没有真正带来太多优势-i。例如,如果您希望abc匹配区分大小写而uyx不是区分大小写,则可能会更有趣,您可以这样做:

\n
grep -P 'abc|(?i)uyx'\n
Run Code Online (Sandbox Code Playgroud)\n

或者:

\n
grep -P 'abc|(?i:uyx)'\n
Run Code Online (Sandbox Code Playgroud)\n

(以及其他正则表达式语法的等效变体)。

\n

其等效标准如下所示:

\n
grep -e abc -e '[uU][yY][xX]'\n
Run Code Online (Sandbox Code Playgroud)\n

(请记住,不区分大小写的匹配通常取决于区域设置;例如,大写是否iI可能\xc4\xb0取决于区域设置grep -i i)。

\n