I want to use sed to print the text between the last occurrence of a pattern and an empty line. For example, in the following file:
$ cat file
pattern
1
2
3
pattern
4
5
pattern
6
7
8
9
10
11
I want to print only
6
7
8
9
I tried sed '/pattern/{:1;$!{/^$/!{N;b1};h}};${x;p};d' file from here, but it does not work.
Edit: This almost works:
$ sed -n -e '/pattern/ {n; :a; $!{/\n$/!{N;ba};h} }; $ { x;p }' file
6
7
8
9
How can one delete the empty line at the end?
Edit2: Here is a solution that works:
$sed '/pattern/{:1;$!{/\n$/!{N;b1};h}};${x;s/pattern\n//;s/\n$//;p};d' file
6
7
8
9
Edit3: This is even better:
$sed '/pattern/{:1;$!{/\n$/!{N;b1};s///;h}};${x;s/pattern\n//;p};d' file
/END/is matched against the accumulated lines in the pattern space, rather than the current line. So try setting/END/as/\n$/rather than/^$//END/has to get pulled into the pattern space in order to match it. You could always just substitute it away - either before pushing the pattern space into the hold buffer (s/\n$//;h) or after swapping it back out with (x;s/\n$//)hyou can abbreviate it tos///;h(the empty pattern//re-uses the earlier/\n$/)