Description
In the following example, many lines contain LIBS=, we want to delete all but the last one of them.
Raw Input Desired Output
 1 LIBS=-lm
 2 some other data
 3 HEADERS=stdlib.h math.h
 4 some other data
 5 LIBS=-lz -lm
 6 some other data
 7 HEADERS=stdlib.h math.h zlib.h
 8 some other data
 9 LIBS=-lz -lm -ld
10 some other data
11 some other data
12 HEADERS=stdlib.h math.h zlib.h regex.h
13 some other data
 2 some other data
 3 HEADERS=stdlib.h math.h
 4 some other data
 6 some other data
 7 HEADERS=stdlib.h math.h zlib.h
 8 some other data
 9 LIBS=-lz -lm -ld
10 some other data
11 some other data
12 HEADERS=stdlib.h math.h zlib.h regex.h
13 some other data
Script and Comments
Script1
[ 1] /LIBS=/!b
[ 2] :loop
[ 3] $q
[ 4] N
[ 5] /\n[^\n]*LIBS=[^\n]*$/!b loop
[ 6] s/^[^\n]*\n//
[ 7] h
[ 8] s/\n[^\n]*$//p
[ 9] x
[10] s/^.*\n//
[11] b loop
Comments
  1. All lines before the first one containing LIBS= are printed by Step [1].
  2. A line containing LIBS= should be deleted if one of the following lines contains LIBS=, this is implemented by the loop consisting of Steps [2] thru [11]:
    • If the last line of the datafile has been reached, command `q' of Step [3] terminates sed after print the contents of PS;
    • otherwise, Step [4] appends the next line to PS.
    • If the recently appended line does not contains LIBS=, Step [5] makes sed branch to Step [2];
    • Otherwise, the first and the last line of PS now both contains LIBS=:
      • we are sure that the first line of PS is not the last one containing LIBS=, it can be safely deleted by Step [6].
      • Then, Steps [7] thru [10] are used to print then delete all but the last lines of PS.