Raw Input Desired Output
Line 1
Line 2 PAT
Line 3
Line 4 
Line 5
Line 6
Line 7 PAT
Line 8
Line 9
Line 10
Line 11
Line 1
Line 6
Line 11
Script and Comments
Script1
[ 1] /PAT/!b
[ 2] $!N
[ 3] $!N
[ 4] $!N
[ 5] d
Comments
  1. If a line does NOT containing `PAT' (as /PAT/! implies) and is not one of the next three lines following a line containing `PAT', command `b' of Step [1] will perform on it, where sed prints it and then starts a new cycle.
    Note that command `b' without a specified destination makes sed print the contents of PS, then start a new cycle.
  2. When the contents of PS is a line containing `PAT', to delete three following lines, we have to
    • append the next three lines to PS via three `N' commands,
    • then, command `d' empties PS and starts a new cycle.
    • When the last line of a file has been read, command `N' makes sed print the contents of PS then terminate, but this is not what we desire. Therefore, we precede command `N' of Step [2] (and [3], too) with $! to instruct sed not to perform command `N' on the last line of a file.
  3. To delete N lines following the one containing `PAT', there must be N-1 $!N commands preceding the last command `d'. The following script uses a loop instead.
Script2
[ 1] /PAT/!b
[ 2] :loop
[ 3] $!{
[ 4] N
[ 5] /(\n[^\n]*){3}/!b loop
[ 6] }
[ 7] d
Comments -r
  1. Steps [2] thru [6] constitute a loop which iterates until PS has four lines (the original line and three following ones) or the end of the file is reached.
  2. PS has four lines if it contains exactly three newline characters, and
    • ^([^\n]*\n){3}[^\n]*$ can be used to test.
    • Since PS will not have more than four lines during the execution of this script, (\n[^\n]*){3} is sufficient.