Description
In the following example, we want to replace every 'CLASS=...' with the first 'CLASS=...' in the file.
Raw Input Desired Output
NOTE=mandatory
CLASS=coreutils
CMD=whoami

CLASS=fileutils CMD=chmod
NOTE=mandatory CLASS=textutils CMD=tr
NOTE=mandatory
CLASS=coreutils
CMD=whoami

CLASS=coreutils CMD=chmod
NOTE=mandatory CLASS=coreutils CMD=tr
Script and Comments
Script1
[ 1] /^CLASS=/!b
[ 2] h
[ 3] :loop
[ 4] /^CLASS=/g
[ 5] n
[ 6] b loop
Comments
  1. For any line before the first one containing 'CLASS=', command 'b' of step [1] will make sed branch to the end of script, print that line out, then start a new cycle.
  2. The first line containing 'CLASS=' will be kept in Hold Space by command 'h' of Step [2].
  3. Step [3] thru Step [6] constitute a loop. It is used to process lines from the first one containing 'CLASS=' till end of file:
    • If a line contains 'CLASS=', command 'g' of Step [4] will overwrite it(Pattern Space) with that line kept in Hold Space previously.
    • Otherwise, no changes will be made.
    • Command 'n' of Step [5] will print the contents of Pattern Space, read next line, then Step [6] makes sed branch to Step [3].