我想找到有“abc”和“efg”的文件,这两个字符串在该文件中的不同行。一个包含以下内容的文件:
blah blah..
blah blah..
blah abc blah
blah blah..
blah blah..
blah blah..
blah efg blah blah
blah blah..
blah blah..
应该匹配。
我想找到有“abc”和“efg”的文件,这两个字符串在该文件中的不同行。一个包含以下内容的文件:
blah blah..
blah blah..
blah abc blah
blah blah..
blah blah..
blah blah..
blah efg blah blah
blah blah..
blah blah..
应该匹配。
当前回答
随着几个月前ugrep的发布:
ugrep 'abc(\n|.)+?efg'
这个工具是高度优化的速度。它也是GNU/BSD/PCRE-grep兼容的。
注意我们应该使用惰性重复+?,除非您想将所有efg行匹配在一起,直到文件中的最后一个efg。
其他回答
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
我在几天前发布了一个grep替代方案,它直接支持这一点,通过多行匹配或使用条件——希望它对搜索这里的人有用。下面是示例命令的样子:
多行:
sift -lm 'abc.*efg' testfile
条件:
sift -l 'abc' testfile --followed-by 'efg'
你也可以指定'efg'必须在一定的行数内跟在'abc'后面:
sift -l 'abc' testfile --followed-within 5:'efg'
你可以在sift-tool.org上找到更多信息。
在所有文件中递归搜索(在每个文件中的多行中),同时存在两个字符串(即string1和string2在不同的行中,并且都存在于同一个文件中):
grep -r -l 'string1' * > tmp; while read p; do grep -l 'string2' $p; done < tmp; rm tmp
在所有文件中递归搜索(在每个文件中的多行中),使用EITHER字符串存在(即string1和string2在不同的行中,并且在同一个文件中存在):
grep -r -l 'string1\|string2' *
sed应该足够了,就像海报LJ上面说的,
而不是!d,你可以简单地使用p打印:
sed -n '/abc/,/efg/p' file
下面是一种连续使用两个grep的方法:
egrep -o 'abc|efg' $file | grep -A1 abc | grep efg | wc -l
返回0或正整数。
egrep -o(只显示匹配,技巧:同一行上的多个匹配会产生多行输出,就好像它们在不同的行上一样)
grep -A1 abc(打印abc及其后面的行) Grep efg | wc -l(在ABC之后的相同或后面的行中发现的efg行数为0-n,结果可用于'if") 如果需要模式匹配,可以将Grep更改为egrep等