linux - 使用 grep regex 搜索多行模式

标签 linux awk sed grep

我是 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/

相关文章:

linux - 含义 警告 "File is touched by more than one package"

node.js - 在 linux 中运行 "Hello World" Electron 应用程序

linux - 如何在sed中用 "N/A"替换 "0"数据?

linux - 当从 cron 调用脚本时,脚本中的 Sed 命令不起作用

bash - 使用 sed 删除 CSV 列中的字符

linux - 如何在窗口上构建 mlpack

c++ - AWK中的大整数只有53位吗?

bash - 添加从命令输出中提取的时间的分钟

linux - 提取冒号后引号之间的值

linux - redsocks + iptables 行为