Raw Input Desired Output


Line 4
Line 5
Line 6
Line 4
Line 5
Line 6
Script and Comments
Script1
[ 1] /^$/{
[ 2] $d
[ 3] N
[ 4] /\n$/D
[ 5] s/\n//
[ 6] }
[ 7] :loop
[ 8] n
[ 9] b loop
Comments
  1. Flowchart:
  2. 'Pattern space' is abbreviated to 'PS'.
  3. Step [7] thru [9] constitute a loop. What this loop does is using command 'n' to print the content of PS(the current line) and then read in next line.
  4. If the first line of a file is not blank, sed will go to the loop made up of Step [7] thru [9].
  5. If the first line of a file is blank, sed will
    • Append next line.
    • Discard the first (blank) line in PS.
    • Enter the loop mentioned above if the newly appended line is not blank; otherwise go to Step [2]
    • Using command 'D' here is a little bit tricky.
Script2
[ 1] /./,$!d
Comments
  1. This elegant solution (reference: sed-1-liner) makes use of the '2-address' mechanism of sed.
  2. The 2-address
    /./,$
    stands for
    the first non-blank line till the end of file
    thus 'splits' the data file into two parts:
    • Leading part full of blank lines
    • the first non-blank lines till the end.