我想找到有“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..
应该匹配。
当前回答
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
其他回答
如果可以使用Perl,就可以很容易地做到这一点。
perl -ne 'if (/abc/) { $abc = 1; next }; print "Found in $ARGV\n" if ($abc && /efg/); }' yourfilename.txt
您也可以使用单个正则表达式来实现这一点,但这涉及到将文件的整个内容放入单个字符串中,对于大型文件,这可能会占用太多内存。 为了完整起见,下面是该方法:
perl -e '@lines = <>; $content = join("", @lines); print "Found in $ARGV\n" if ($content =~ /abc.*efg/s);' yourfilename.txt
如果您对模式序列不感兴趣,可以使用grep。
grep -l "pattern1" filepattern*.* | xargs grep "pattern2"
例子
grep -l "vector" *.cpp | xargs grep "map"
Grep -l将找到与第一个模式匹配的所有文件,xargs将为第二个模式查找Grep。希望这能有所帮助。
如果你对你要找的两个字符串'abc'和'efg'之间的距离有一些估计,你可以使用:
grep -r . -e 'abc' -A num1 -B num2 | grep 'efg'
这样,第一个grep将返回'abc' + #num1行,后面是#num2行,第二个grep将筛选所有这些以获得'efg'。 然后您将知道它们同时出现在哪些文件中。
这应该可以工作:
cat FILE | egrep 'abc|efg'
如果有多个匹配项,可以使用grep -v过滤掉
用银搜索器:
ag 'abc.*(\n|.)*efg' your_filename
与戒指持有者的答案相似,但用ag代替。银色搜索者的速度优势可能在这里大放异彩。