搜索 foo 和 bar

7 grep search

我正在寻找一个命令选项grep来查找出现foo和 的文件bar

grep -r -e foo -e bar .
Run Code Online (Sandbox Code Playgroud)

显示只有foo或只有的bar文件和有foo和的文件bar

是否有可能与grep只找到其中有两个文件foobar(并显示线相匹配的任一foobar或两者在这些文件)?

例子:

echo foo > file1
echo bar > file2
(echo foo;echo;echo bar) >file3
echo barfoo > file4
Run Code Online (Sandbox Code Playgroud)

grep cmd:

grepcmd -r -e foo -e bar .
./file3:foo
./file3:bar
./file4:barfoo
Run Code Online (Sandbox Code Playgroud)

Sté*_*las 10

查找包含两者的文件

(假设 GNU grep/ xargs

grep -rl --null abc . | xargs -r0 grep -l bcd
Run Code Online (Sandbox Code Playgroud)

如果你想看到包含线abcbcd或两者同时包含的文件abcbcd

grep -rl --null abc . |
  xargs -r0 grep -l --null bcd |
  xargs -r0 grep -He abc -e bcd
Run Code Online (Sandbox Code Playgroud)

匹配线同时包含:

grep -re 'foo.*bar' -e 'bar.*foo' .
Run Code Online (Sandbox Code Playgroud)

只要模式不重叠,就可以工作。

grep -re 'abc.*bcd' -e 'bcd.*abc' .
Run Code Online (Sandbox Code Playgroud)

将无法找到包含abcd.

如果您grep-PPCRE:

grep -rP '^(?=.*abc).*bcd' .
Run Code Online (Sandbox Code Playgroud)

会工作。

或者,POSIXly:

find . ! -type d -exec awk '/abc/ && /bcd/ {print FILENAME ":" $0}' {} +
Run Code Online (Sandbox Code Playgroud)

您还可以使用agrep

agrep -r 'abc;bcd' .
Run Code Online (Sandbox Code Playgroud)