Raw Input Desired Output
line 1
line 2 PAT
line 3
line 4 PAT
line 5
line 6
line 7 PAT
line 8
line 9 PAT
line 10
line 11
line 9 PAT
line 10
line 11
Script and Comments
Script1
[ 1] /PAT/!d
[ 2] :loop
[ 3] $q
[ 4] N
[ 5] s/^.*\n\([^\n]*PAT\)/\1/
[ 6] b loop
Comments
  1. `Pattern Space' is abbreviated to `PS'.
  2. Step [1] is used to skip all lines before the first one containing PAT.
  3. Steps [2] thru [6] constitute a loop, which:
    • repeats joining to PS the lines following the one containing PAT until another one is reached.
    • When the last line read by Step [4] containing PAT, Step [5] will delete all lines of PS except the last one.
    • during the iterations of this loop, the first line of PS contains PAT.
Script2
[ 1] /PAT/!d
[ 2] :loop
[ 3] N
[ 4] s/^.*\n\([^\n]*PAT\)/\1/
[ 5] b loop
Comments
  1. When performs command `N' on the last line of a file, GNU sed will print the contents of PS then terminates. Using this feature, Step [3] of Script1 can be removed.