1
votes

Using awk or sed how can I select lines which are occurring between two different marker patterns? There may be multiple sections marked with these patterns but want only the last one to get printed.

For example: Suppose the file contains:
abc
def1
ghi1
jkl1
mno
abc
def2
ghi2
jkl2
mno
pqr
stu

And the starting pattern is abc and ending pattern is mno So, I need the output as:

def2
ghi2
jkl2

Not sure how to get this.

2
I didn't mean that seriously:: tac file | sed -n '/mno/,/abc/{/mno/d;/abc/q;p}' | tacCyrus
@Cyrus: Why not?user unknown
@userunknown: It's ugly because the whole file has to fit in memory.Cyrus
most text files fit flawlessly into memory.user unknown
@GauravM: Is the length of the interesting section always the same?user unknown

2 Answers

1
votes

Could you please try following awk and let me know if this helps you.

awk '/mno/{flag="";next} /abc/{val="";flag=1;next} flag{val=val?val ORS $0:$0} END{print val}'  Input_file

Solution 2nd:

awk '/abc/{val=""}/abc/,/mno/{if($0~/mno/||$0~/abc/){next};val=val?val ORS $0:$0}END{print val}'  Input_file
1
votes

With gnu sed

sed '
  $bB
  :C
  /^abc$/!d
  :A
  $bB
  N
  /\nabc$/s/.*\n//
  /\nmno$/!bA
  s/[^\n]*\n\(.*\)\n[^\n]*/\1/
  h
  N
  s/.*\n//
  bC
  :B
  g
  /./!d
' infile