Description
If there are nothing except blanks, newline characters between PAT1 and PAT2, reduces them to just one newline character.
Raw Input Desired Output
=== PAT1  

       PAT2 === PAT 1 ... ... PAT 2 === PAT1         PAT2 === PAT1 ... ... ... PAT2 --- PAT1

PAT2 ---
=== PAT1
PAT2 ===
PAT 1 ...
...
PAT 2 === PAT1
PAT2 === PAT1 ...
...
... PAT2 --- PAT1
PAT2
---
Script and Comments
Script1
[ 1] :top
[ 2] /PAT1/!b
[ 3] :loop
[ 4] $q
[ 5] N
[ 6] /\n *$/b loop
[ 7] /\n *PAT2[^\n]*$/b matched
[ 8] h
[ 9] s/\n[^\n]*$//p
[10] x
[11] s/^.*\n//
[12] b top
[13] :matched
[14] s/PAT1( *\n *)*PAT2/PAT1\nPAT2/
[15] P
[16] D
Comments -r
  1. If a line does not end with PAT1 with optional trailing blanks, Step [2] prints it and then starts a new cycle.
  2. Otherwise, Step [5] appends the next line to PS.
  3. If the line appended by Step [5] is
    • an empty one or consisting of only blanks, then sed jumps back to Step [3] to append the next line.
    • a line begins with PAT2 with optional leading blanks, then PS contains what we want to reduce; therefore, sed jumps to Step [13].
    • otherwise, there is nothing to reduce in PS up to the PAT2 found. Note that there may be another PAT1 behind it. So we use steps [8] thru [12] to:
      • print all but the last line of PS,
      • delete all but the last line, and
      • then make jumps back to Step [1] to treat the last line of PS the same as a line read by a new cycle.
  4. Step [14] reduces the blanks and the empty lines between PAT1 and PAT2. Since there may exist another PAT1 after the PAT2 found, so we have to treat the last line of PS the same as a line read by a new cycle via Steps [14] and [15].
Script2
[ 1] /PAT1/!b
[ 2] :loop
[ 3] $q
[ 4] N
[ 5] /\n *$/b loop
[ 6] /\n *PAT2[^\n]*$/b matched
[ 7] h
[ 8] s/\n[^\n]*$//p
[ 9] x
[10] s/^.*\n/\n/
[11] D
[12] :matched
[13] s/PAT1( *\n *)*PAT2/PAT1\nPAT2/
[14] P
[15] D
Comments
  1. The label :topof Script1 is only referenced by Step [12]. This script removes it by replacing Steps [11] and [12] with Steps [10] and [11].