-1

我想提取两种模式之间的线条(例如,模式 1 和模式 2)。该文件的结构如下:

a random number of lines containing other stuff
pattern1
some lines to be extracted (finding out the number of lines possible, if necessary)
pattern2
a random number of lines containing other stuff
pattern1
some lines to be extracted
pattern2
a random number of lines containing other stuff

这会重复很多次(即存在大量匹配的pattern1-pattern2 对)。我想提取所有匹配模式之间的线条,有效地丢弃随机的东西。

我怎样才能做到这一点?

4

4 回答 4

2
sed -n "/pattern1/,/pattern2/ {
 /pattern1/ !{
   /pattern2/ !p
   }
 }" InputFile

印刷线 BETWEEN 图案,不包括图案本身

于 2013-11-11T09:30:10.523 回答
2

使用awk

awk '/pattern1/,/pattern2/'
pattern1
some lines to be extracted (finding out the number of lines possible, if necessary)
pattern2
pattern1
some lines to be extracted
pattern2

图案之间只有线条

awk '/pattern2/ {f=0;next} f; /pattern1/ {f=1}'
some lines to be extracted (finding out the number of lines possible, if necessary)
some lines to be extracted
于 2013-11-08T12:26:32.273 回答
1

您可以sed为此使用:

cat inputfile | sed -ne '/pattern1/,/pattern2/p'
于 2013-11-08T12:23:32.333 回答
1

这是awk中的另外两个:

/pattern1/ {inside_block=1}
/pattern2/ {inside_block=0}
inside_block==1 {print $0}

或者

/pattern1 { print $0; while(getline > 0) {print $0;if (/pattern2/) break }}

两者都不像发布的解决方案那样优雅,但根据程序的其他要求或模式的复杂性,两者都可能有用。

于 2013-11-08T12:31:46.947 回答