Raw Input
line 1
-- first pair --
line 3
--
one more pair
--
line 7
line 8 -- more -- and -- more
--
line 9
Desired Output
line 1
BEGIN first pair END
line 3
BEGIN
one more pair
END
line 7
line 8 BEGIN more END and BEGIN more
END
line 9
Script and Comments
Script1
[ 1] :loop1
[ 2] s/PAT/OBJ1/
[ 3] t loop2
[ 4] n
[ 5] b loop1
[ 6] :loop2
[ 7] s/PAT/OBJ2/
[ 8] t loop1
[ 9] n
[10] b loop2
Comments
  1. This script will replace
    • (2n+1)th occurrence of PAT with OBJ1,
    • (2n)th occurrence of PAT with OBJ2, where n is a natural number.
  2. Flowchart:
  3. Note that in Step [2] and [7], we do not use the 'g' modifier of command 's'.
  4. This script works well even when multiple occurrences of PAT exists in a line.