Description
In the example, we want to replace every occurrence of word with six dashes except the last three occurrences of a file.
Raw Input Desired Output
word_1 
much more data...
word_2 word_3 word_4
much more data...
word_5
word_6 word_7
much more data...
word_8 final word_9
------_1 
much more data...
------_2 ------_3 ------_4
much more data...
------_5
------_6 word_7
much more data...
word_8 final word_9
Script and Comments
Script1
[ 1] /word/!b
[ 2] :0
[ 3] /(word.*){4}/!{
[ 4] $!N
[ 5] $!b 0
[ 6] }
[ 7] :1
[ 8] s/word((.*word){3})/------\1/
[ 9] t 1
[10] $q
[11] :2
[12] /^[^\n]*word/!{
[13] P
[14] s/^[^\n]*\n//
[15] b 2
[16] }
[17] b 0
Comments
  1. The `-r' option of GNU sed must be used to make sed interpret REs as EREs.
  2. The Pattern Space is abbreviated to PS.
  3. If an occurrence of word is followed by three or more occurrences, we are sure that it is NOT one of the last three ones; therefore, we can replace it safely.
  4. A datafile is divided into to parts: lines before the one containing the first word, and the others.
  5. For each line before the line containing the first word, Step [1] prints it and then sed starts a new cycle.
  6. After the line containing the first word was read to PS, the loop consisting of Steps [2] thru [6] keeps appending lines to PS until there are at least four occurrences of word.
  7. Steps [7] thru [9] constitute a loop which replaces all but the last third occurrences of word in PS.
  8. After substitutions, there may be no words in the first several lines of PS. In this case, Steps [11] thru [16] print and then delete them.
  9. Step [17] makes sed jump to Step [2].