我是 linux 的新手,我想在文件中搜索以“Leonard is”开头并以“champion”结尾的模式
这个模式也可以放在多行
输入文件 (input.txt) 可能如下所示:
1 rabbit eats carrot Leonard is a champion
2 loin is the king of
3 jungle Leonard is a
4 Champion
5 Leonard is An exemplary
6 Champion
我希望所有出现的模式都忽略输出文件中模式以外的所有其他字符:
1 Leonard is a champion
3 Leonard is a
4 Champion
5 Leonard is An exemplary
6 Champion
我已经非常接近以下命令:
cat input.txt | grep -ioE "Leonard.*Champion$"
因为这个命令只返回
1 Leonard is a champion
忽略多行中出现的所有模式
如果除 grep 之外的任何其他搜索方法有用,请告诉我谢谢!!
最佳答案
Perl 来拯救:
perl -l -0777 -e 'print for <> =~ /(.*Leonard(?s:.*?)[Cc]hampion.*)/g' -- input.txt
-
-l
在打印中添加换行符 -
-0777
读取整个文件而不是逐行处理 - 钻石运营商
<>
读取输入 -
.*?
就像.*
,即它匹配任何东西,但?
意味着尽可能短的匹配就足够了。这可以防止正则表达式匹配第一个 Leonard 和最后一个冠军之间的所有内容。 -
.
在正则表达式中通常不匹配换行符,但它与s
匹配修饰符。(?s:.*?)
本地化更改的行为,因此其他点仍然不匹配换行符。
关于linux - 使用 grep regex 搜索多行模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50578994/