【发布时间】:2019-09-07 18:20:06
【问题描述】:
我有一个想用 bash 处理的文件。可以使用 awk、sed 或 grep 或类似的。该文件在一行中有多次出现。我想提取这两次出现之间的所有内容并将输出分别打印在单独的行上。
我已经尝试过使用这个:
cat file.txt | grep -o 'pattern1.*pattern2'
但这会打印从 pattern1 到最后一个匹配 pattern2 的所有匹配项。
$ 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
【问题讨论】:
-
您的输入中可以包含
foo pattern1 bar pattern2或pattern1 foo pattern1 bar pattern2或pattern1 foo pattern2 bar pattern2吗?如果是这样,请在您的问题中包含这些案例并显示每个案例的预期输出。 -
我重新打开了这个,因为另一个问题是以前作为 (stackoverflow.com/questions/3027518/…) 的副本关闭的另一个问题是询问跨多行匹配,这是一个比行内更容易解决的问题,它没有'不包含标准 UNIX 工具的解决方案,仅适用于带有实验性 -P 选项的 perl 或 GNU grep,并且有更好(更简单、更高效、更便携、更健壮)的跨行匹配解决方案。