Description
A block begins with a line of the form # begin and ends with a line of the form # end. We want to replace every block containing `this' with the following lines:
HAS BEEN
MODIFIED
Raw Input Desired Output
line 1
line 2
# begin
 replace this
 block
# end
line 7
line 8
# begin
 keep the
 block
# end
line 13
line 1
line 2
# begin
 HAS BEEN 
 MODIFIED 
# end
line 7
line 8
# begin
 keep the
 block
# end
line 13
Script and Comments
Script1
[ 1] /^# begin$/!b
[ 2] :loop
[ 3] N
[ 4] /\n# end$/!b loop
[ 5] /this/s/\n.*\n/\n HAS BEEN \n MODIFIED \n/
Comments
  1. The Pattern Space is abbreviated to `PS'.
  2. Any line not belonging to a block will be printed by the command `b' of Step [1], which will make sed start a new cycle.
  3. Once the first line of a block is read, the loop consisting of Steps [2] thru [4] will append all the other lines of the block to the PS, where every two adjacent lines are separated by a newline character.
  4. After Step [4], the PS has all lines of the block in question. If the block contains the string `this', the contents will be replaced by command `s' of Step [5].