Description
We want to replace each of the first four occurrences of word with six dashes.
Raw Input Desired Output
word_1 
much more data...
word_2 word_3
much more data...
word_4 word_5
word_6
much more data...
word_7 final word_8
------_1 
much more data...
------_2 ------_3
much more data...
------_4 word_5
word_6
much more data...
word_7 final word_8
Script and Comments
Script1
[ 1] /word/!b
[ 2] :0
[ 3] $!{
[ 4] N
[ 5] /(word.*){4}/!b 0
[ 6] }
[ 7] :1
[ 8] s/word/------/
[ 9] x
[10] s/^/\n/
[11] /\n{4}/!{
[12] x
[13] /word/b 1
[14] b 2
[15] }
[16] x
[17] :2
[18] n
[19] b 2
Comments
  1. The `-r' option of GNU sed must be used to interpret REs as EREs.
  2. The Pattern Space and the Hold Space are abbreviated to PS and HS, respectively.
  3. Lines before and not including the first one containing word are printed by Step [1].
  4. Once the first line containing word is read, the loop consisting of Steps [2] thru [6] keeps reading and then appending lines to PS till there are 4 words or the end of file is reached.
  5. Then the loop consisting of Steps [7] thru [15] replaces the first four words:
    • HS is used as a counter. Each time a word is replaced, we insert a newline character to HS.
    • Since `s' command only applies to PS instead of HS, Step [9] is essential, which exchanges the contents of PS and HS.
    • If the counter does not have 4 newline characters, \n{4} in Step [11] does NOT match, therefore, Step [12] will be executed. If there are words not replaced, Step [13] makes sed jump back to Step [7].
      Otherwise, the file contain less than 4 words and there are no words not replaced, Step [14] makes sed jump to Step [17] to read and then print the remaining lines.
    • For files containing at least 4 words, after replacing the 4th word and adding a newline to the counter, since \n{4} in Step [11] matches, Steps [12] thru [15] will be skipped.