0

I am trying to print the lines between the last occurrence of two patterns into another file using sed. For example, if file1 contains the following:

StartPattern
1
2
3
EndPattern
4
5
StartPattern
6
7
8
EndPattern
9
10
StartPattern
11
12
13
EndPattern
14
15

I would like the output to be:

11
12
13

How can I do this with sed?

  • cat file|sed -n 'H; /^StartPattern/h; ${g;p;}' |sed '1d' |sed '/EndPattern/q' |sed '$ d' – Emilio Galarraga Sep 26 '17 at 17:26
0

With single awk process:

awk '/StartPattern/{ f=1;r=""; next }f && /EndPattern/{f=0}
     f{ r=(r=="")? $0: r RS $0 }END{ print r }' file > output

output file contents:

11
12
13

Alternative tac + awk solution:

tac file | awk '/StartPattern/{exit}/EndPattern/{f=1;next}f' | tac > output
  • This works if the End Pattern is the last line of the file. I realize my original post (which is now editted) was misleading. How can I only extract what's in between the patterns and not the rest of the file if there are lines below the last EndPattern? – A. B Sep 26 '17 at 16:12
  • @A.B, it will work even if EndPattern is not the last line. You need to test – RomanPerekhrest Sep 26 '17 at 16:14
  • Your first answer (tac+awk) prints: 11 12 13 14 15. However, your new answer (single awk) gives the correct output. – A. B Sep 26 '17 at 16:22
  • @A.B, I can not see the issue. Look here ibb.co/bTqUYk – RomanPerekhrest Sep 26 '17 at 16:27
0
cat file |sed -n 'H; /^StartPattern/h; ${g;p;}' |sed -e '1d' -e '/EndPattern/q' |sed '$ d'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.