Raw Input Desired Output
1
2
3 PAT
4
5 PAT
6
7 PAT
8
9
1
2
3 PAT
4
5 PAT
6
8
9
Script and Comments
Script1
[ 1] /PAT/!b
[ 2] :loop
[ 3] $D
[ 4] N
[ 5] /\n[^\n]*PAT/{
[ 6] h
[ 7] s/\n[^\n]*$//
[ 8] p
[ 9] x
[10] s/^.*\n//
[11] }
[12] b loop
Comments
  1. When a line containing `PAT' is met, this script keeps reading next lines till another line containing `PAT' is read.
  2. The flow chart is shown as follows:
  3. Steps [6] thru [10] do what the block `print then delete all but last lines of PS' does:
    • Step [6] copies contents of PS to HS.
    • Step [7] deletes the last line of PS.
    • Step [8] print contents of PS.
    • Step [9] exchanges contents of PS and HS.
    • Step [10] deletes all but the last line of PS.