我想在两个模式之间提取线条(比如,pattern1和pattern2)。该文件的结构如下:
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对)。我想在所有匹配的模式之间提取线条,有效地丢弃随机的东西。
我该怎么做?
答案 0 :(得分: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
答案 1 :(得分:2)
sed -n "/pattern1/,/pattern2/ {
/pattern1/ !{
/pattern2/ !p
}
}" InputFile
打印线BETWEEN模式,不包括模式本身
答案 2 :(得分:1)
您可以使用sed
:
cat inputfile | sed -ne '/pattern1/,/pattern2/p'
答案 3 :(得分:1)
在awk中还有两个:
/pattern1/ {inside_block=1}
/pattern2/ {inside_block=0}
inside_block==1 {print $0}
OR
/pattern1 { print $0; while(getline > 0) {print $0;if (/pattern2/) break }}
两者都不如发布的解决方案那么优雅,但两者都可能有用,具体取决于程序的其他要求或模式的复杂性。