我想找到有“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..
应该匹配。
当前回答
#!/bin/bash
shopt -s nullglob
for file in *
do
r=$(awk '/abc/{f=1}/efg/{g=1;exit}END{print g&&f ?1:0}' file)
if [ "$r" -eq 1 ];then
echo "Found pattern in $file"
else
echo "not found"
fi
done
其他回答
这可以通过首先使用tr用其他字符替换换行符来轻松完成:
tr '\n' '\a' | grep -o 'abc.*def' | tr '\a' '\n'
这里,我使用警报字符\a (ASCII 7)来代替换行符。 这在你的文本中几乎找不到,而且grep可以用一个.匹配它,或者专门用\a匹配它。
awk一行程序:
awk '/abc/,/efg/' [file-with-content]
#!/bin/bash
shopt -s nullglob
for file in *
do
r=$(awk '/abc/{f=1}/efg/{g=1;exit}END{print g&&f ?1:0}' file)
if [ "$r" -eq 1 ];then
echo "Found pattern in $file"
else
echo "not found"
fi
done
下面是一个受到这个答案启发的解决方案:
如果'abc'和'efg'可以在同一行: Grep -zl 'abc。*efg' <您的文件列表> 如果'abc'和'efg'必须在不同的行上: grep -Pzl '(?s)abc.*\n.;*efg' <您的文件列表>
参数:
-P使用perl兼容的正则表达式。 将输入视为一组行,每一行以0字节结束,而不是换行符。例如,grep将输入视为一行。注意,如果你不使用-l,它将显示匹配后的NUL字符,见注释。 -l list只匹配文件名。 (?s)激活PCRE_DOTALL,这意味着'。'查找任何字符或换行符。
用银搜索器:
ag 'abc.*(\n|.)*efg' your_filename
与戒指持有者的答案相似,但用ag代替。银色搜索者的速度优势可能在这里大放异彩。