首页 > 解决方案 > 如何在不同的行上打印多个图案

问题描述

我有一个想用 bash 处理的文件。可以使用 awk、sed 或 grep 或类似的。该文件在一行中有多次出现。我想提取这两次出现之间的所有内容,并将输出分别打印在单独的行上。

我已经尝试过使用这个:

cat file.txt | grep -o 'pattern1.*pattern2'

但这将打印从模式 1 到最后一个匹配模式 2 的所有匹配项。

$ cat file.txt
pattern1 this is the first content pattern2 this is some other stuff pattern1 this is the second content pattern2 this is the end of the file.

我想得到:

pattern1 this is the first content pattern2
pattern1 this is the second content pattern2

标签: bashawksedgrep

解决方案


尝试 gnu sed:

 sed -E 's/(pattern2).*(pattern1)(.*\1).*/\1\n\2\3/' file.txt

推荐阅读