Raw Input Desired Output
Line 1 AAA
Line 2 BBB
Line 3 CCC
Line 4 DDD
Line 5 EEE
Line 6 FFF
Line 7 GGG
Line 8 HHH
Line 9 III
Line 10 JJ
Line 11 KK
Line 1 AAA
Line 2 BBB
Line 3 CCC
Line 4 DDD
----------
Line 5 EEE
Line 6 FFF
Line 7 GGG
Line 8 HHH
----------
Line 9 III
Line 10 JJ
Line 11 KK
Script and Comments
Script1
[ 1] x
[ 2] s/$/#/
[ 3] /#\{4\}/{
[ 4] a\
[ 5] ----------
[ 6] s/.*//
[ 7] }
[ 8] x
Comments
  1. 'Pattern space' and 'hold space' are abbreviated to 'PS' and 'HS', respectively.
  2. This script will add a line '----------' after every fourth line. You can change the '4' in this script to arbitrary number you like.
  3. We use the concept of 'counter' and keep the counter's value as a sequence of '#'s in HS. For example, '####' stands for the value 4. Each time a line is read in, we add a '#' to the counter.
  4. Step [1] swaps the contents of PS and HS. After Step [1], the line read from the datafile is kept in HS.
  5. From Step [4] thru [6], the contents of PS is the counter's value.
  6. Step [3] thru [6] will be executed only when the counter's value is 4. This block will
    • send a line '----------' to the standard output at the end of this cycle (Step [4]-[5]).
    • reset the counter to zero (Step [6]).
  7. Step [8] will put the line read from the datafile back to PS, and the default action of sed will print it out.
Script2
[ 1] G
[ 2] /\n\{4\}$/a\
[ 3] ----------
[ 4] P
[ 5] s/^[^\n]*\(\n\{4\}\)*//
[ 6] h
[ 7] d
Comments
  1. This script uses a different approach: instead of using '#'s, it uses newline characters to keep the counter's value.
  2. After Step [1], PS consists of two parts:
    • the first one is the line read from the datafile, and
    • the trailing newlines are the value of the 'counter'.
    The increment of the counter is done by Step [1].
  3. If the counter's value is 4, i.e., 4 trailing newlines in PS, Step [2] will send the line '----------' to the stdout at the end of this cycle.
  4. Step [4] will print the line read from the datafile.
  5. Step [5] will
    • remove non-newline characters, and
    • reset the counter to zero if its value is 4.
  6. Step [6] will copy the counter's value to HS.
  7. Step [7] is used to start next cycle.