如何从管道中 grep 多个模式

bit*_*bit 4 shell grep quoting regular-expression

我想在列表中找到三个模式。我试着打字

$ pip3 list | grep -ei foo -ei bar -ei baz
Run Code Online (Sandbox Code Playgroud)

但是外壳会抛出一个broken pipe error和一个大的Traceback.

我如何处理grep从通过管道传输到的列表中传递的多个模式grep

Kus*_*nda 8

原因

grep -ei foo -ei bar -ei baz
Run Code Online (Sandbox Code Playgroud)

不起作用是因为该-e选项的语义是-e PATTERN,如

grep -i -e foo -e bar -e baz
Run Code Online (Sandbox Code Playgroud)

...这就是命令的样子。该-i选项(用于不区分大小写的匹配)只需要指定一次并且会影响所有模式。

随着-ei foo您要求在文件中grep查找模式。ifoo

“断管”错误来自pip3尝试写入死管的末端。管道已死,因为grep找不到文件foobarbaz并已终止(出现三个“未找到文件”错误)。回溯来自pip3哪个 Python 程序(因此它可以准确地告诉您 Python 代码中错误发生在其一侧的哪个位置)。


mau*_*wns 7

尝试:

pip3 list | grep -Ei 'foo|bar|baz'
Run Code Online (Sandbox Code Playgroud)

这是来自我的 Arch 服务器的真实示例:

pip3 list | grep -Ei 'ufw|set'
setuptools 40.0.0 
ufw        0.35   
Run Code Online (Sandbox Code Playgroud)

操作系统和grep信息:

uname -a
Linux archlinux 4.16.6-1-ARCH #1 SMP PREEMPT Mon Apr 30 12:30:03 UTC 2018 x86_64 GNU/Linux

grep --version
grep (GNU grep) 3.1
Copyright (C) 2017 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

Written by Mike Haertel and others, see <http://git.sv.gnu.org/cgit/grep.git/tree/AUTHORS>.
Run Code Online (Sandbox Code Playgroud)

  • 请注意,`egrep` 已被弃用,取而代之的是 `grep -E`,因为它的价值。 (2认同)