sed: cat -s

1 
1 7.20 Squeezing Blank Lines
1 ==========================
1 
1 As a final example, here are three scripts, of increasing complexity and
1 speed, that implement the same function as 'cat -s', that is squeezing
1 blank lines.
1 
1    The first leaves a blank line at the beginning and end if there are
1 some already.
1 
1      #!/usr/bin/sed -f
1 
1      # on empty lines, join with next
1      # Note there is a star in the regexp
1      :x
1      /^\n*$/ {
1      N
1      bx
1      }
1 
1      # now, squeeze all '\n', this can be also done by:
1      # s/^\(\n\)*/\1/
1      s/\n*/\
1      /
1 
1    This one is a bit more complex and removes all empty lines at the
1 beginning.  It does leave a single blank line at end if one was there.
1 
1      #!/usr/bin/sed -f
1 
1      # delete all leading empty lines
1      1,/^./{
1      /./!d
1      }
1 
1      # on an empty line we remove it and all the following
1      # empty lines, but one
1      :x
1      /./!{
1      N
1      s/^\n$//
1      tx
1      }
1 
1    This removes leading and trailing blank lines.  It is also the
1 fastest.  Note that loops are completely done with 'n' and 'b', without
1 relying on 'sed' to restart the script automatically at the end of a
1 line.
1 
1      #!/usr/bin/sed -nf
1 
1      # delete all (leading) blanks
1      /./!d
1 
1      # get here: so there is a non empty
1      :x
1      # print it
1      p
1      # get next
1      n
1      # got chars? print it again, etc...
1      /./bx
1 
1      # no, don't have chars: got an empty line
1      :z
1      # get next, if last line we finish here so no trailing
1      # empty lines are written
1      n
1      # also empty? then ignore it, and get next... this will
1      # remove ALL empty lines
1      /./!bz
1 
1      # all empty lines were deleted/ignored, but we have a non empty.  As
1      # what we want to do is to squeeze, insert a blank line artificially
1      i\
1 
1      bx
1