Description
  • The contents between 'BEGIN' and its matching 'END' may span several lines.
  • Besides, there may exist several BEGIN-END pairs in a line.
  • The following script does not take nested pairs into consideration.
Raw Input
word-A BEGIN word-B
word-C word-D
word-E END word-F
word-G
word-H BEGIN word-I END word-J BEGIN word-K
word-L word-M
END word-N
word-O
Desired Output
 word-B
word-C word-D
word-E 
 word-I 
 word-K
word-L word-M
Script and Comments
Script1
[ 1] /BEGIN/!d
[ 2] s/BEGIN/\n/
[ 3] s/^.*\n//
[ 4] /END/{
[ 5] s/END/\n/
[ 6] P
[ 7] D
[ 8] }
[ 9] :loop
[10] H
[11] $d
[12] N
[13] s/^.*\n//
[14] /END/!b loop
[15] s/END/\n/
[16] H
[17] x
[18] s/^\n\(.*\)\n.*/\1/
[19] p
[20] s/^.*//
[21] x
[22] D
Comments
  1. Pattern Space and Hold Space are abbreviated to PS, and HS, respectively.
  2. Step [1] is used to delete lines between last 'END' and next 'BEGIN'.
  3. Steps [2] and [3] are used to trim words till and including the first 'BEGIN'. Remember that there may exist several BEGIN-END pairs in a line.
  4. If the current line contains a 'END', Steps [4] thru [8] will:
    • print words of between that pair,
    • remove that pair from current line,
    • then branch to Step [1].
  5. Otherwise, we have to keep all lines till a 'END' is found. Step [9] thru [22] are used to do this job.
  6. To ease explanation, lines are kept in 'X'. 'X' may resides in either PS or HS.
  7. Initially, 'X' resides in HS.
  8. Since the current line does not contain 'END',
    • we append it to 'X' by Step [10],
    • append the next line to current one by command N(Step [12]),
    • then delete the old one by Step [13].
    • if the new line does not contain 'END', repeat the above steps by branching to Step [9].
  9. Now we have a line containing 'END', assume that the current line consists of B END C, and 'A' is used to stands for lines kept:
    After StepCommandPSHS
    14/END/!b loop B END C \n A
    15s/END/\n/ B \n C \n A
    16H B \n C \n A \n B \n C
    17x \n A \n B \n CB \n C
    18s/^\n\(.*\)\n.*/\1/A \n B B \n C
    19p A \n B B \n C
    20s/^.*//   B \n C
    21x B \n C  
    22D C