2

I am trying to to print any text that exists between two different patterns also with this patterns. But only when text between patterns containing particular string [using awk, flag...].

My input file:

START 12.5 elephant dasnbjdai adfad
      s = ad cat da 524a das
      da 54e dog dada 455ad7
      da 45d cow 554s7e
END
START fjs 4 rhino das 452 da
      da = cat da gd 
      das_d pig das 
      4524s dda monkey dasdc4
END 
START da dfsdg cow
      bear dac45
      lion bla bla 
      5as4 fox bla fa jsa
END
START dandsk cow  dada
      bla sheep bla
      fsgv turtle fsd
      da dragon da
END
START
      daadas pig fsv45 
      dasd walrus das 52
END

and my output should be [just show lines between START...END, but containing cat]

START 12.5 elephant dasnbjdai adfad
      s = ad **cat** da 524a das
      da 54e dog dada 455ad7
      da 45d cow 554s7e
END
START fjs 4 rhino das 452 da
      da = **cat** da gd 
      das_d pig das 
      4524s dda monkey dasdc4
END 

How can I print i.e all lines containig dragon and walrus;

Output

START dandsk cow  dada
      bla sheep bla
      fsgv turtle fsd
      da dragon da
END
START
      daadas pig fsv45 
      dasd walrus das 52
END
4

2 回答 2

2

一种方法awk

awk -v RS="END" '$0~/cat/{print $0 RS}' input 

对于第二种情况:

awk -v RS="END" '$0~/walrus|dragon/{print $0 RS}' input 

如果您不希望中间有空行:

awk 'BEGIN{RS="END";ORS=""}$0~/dragon|walrus/{print $0 RS}END{print "\n"}' input
于 2013-06-26T19:49:54.803 回答
0

使用 GNU awk(将 RS 设置为多个字符):

$ gawk 'BEGIN{RS=ORS="\nEND\n"} /dragon|walrus/' file
START dandsk cow  dada
      bla sheep bla
      fsgv turtle fsd
      da dragon da
END
START
      daadas pig fsv45
      dasd walrus das 52
END

或者:

$ awk -v re="dragon|walrus" 'BEGIN{RS=ORS="\nEND\n"} $0~re' file
START dandsk cow  dada
      bla sheep bla
      fsgv turtle fsd
      da dragon da
END
START
      daadas pig fsv45
      dasd walrus das 52
END
于 2013-06-27T02:30:38.590 回答