我想找到有“abc”和“efg”的文件,这两个字符串在该文件中的不同行。一个包含以下内容的文件:

blah blah..
blah blah..
blah abc blah
blah blah..
blah blah..
blah blah..
blah efg blah blah
blah blah..
blah blah..

应该匹配。


当前回答

遗憾的是,你不能。来自grep文档:

grep搜索指定的输入FILEs(或标准输入,如果没有指定文件,或如果给出了一个连字符减号(-)作为文件名),以查找包含与给定PATTERN匹配的行。

其他回答

Grep是这种操作的笨拙工具。

在大多数现代Linux系统中都可以找到pcregrep,可以用作

pcregrep -M  'abc.*(\n|.)*efg' test.txt

where -M,——multiline允许模式匹配多行

还有一个更新的pcre2grep。两者都是由PCRE项目提供的。

pcre2grep可以通过Mac Ports作为pcre2端口的一部分用于Mac OS X:

% sudo port install pcre2 

并通过Homebrew为:

% brew install pcre

或者pcre2

% brew install pcre2

pcre2grep在Linux (Ubuntu 18.04+)上也可用

$ sudo apt install pcre2-utils # PCRE2
$ sudo apt install pcregrep    # Older PCRE

sed应该足够了,就像海报LJ上面说的,

而不是!d,你可以简单地使用p打印:

sed -n '/abc/,/efg/p' file

如果您愿意使用上下文,这可以通过输入来实现

grep -A 500 abc test.txt | grep -B 500 efg

这将显示“abc”和“efg”之间的所有内容,只要它们之间的距离不超过500行。

这个也能用吗?!

perl -lpne 'print $ARGV if /abc.*?efg/s' file_list

$ARGV包含从file_list读取当前文件时的文件名 /s修饰符跨换行搜索。

awk一行程序:

awk '/abc/,/efg/' [file-with-content]