2

How can you delete only single blank lines in sed/vim?

Several questions already address Deleting Blank Lines in ViM, however I want to leave multiple blank lines intact (or as single blank lines), so that:

this

kind

of


thing

Becomes

this
kind
of 

thing
Community
  • 1
  • 1
Bolster
  • 7,460
  • 13
  • 61
  • 96
  • Actually, some of the answers at the post you link to address some of what you want. I bet you could tweak [this answer](http://stackoverflow.com/a/10403658/26702) for example. – Telemachus Dec 02 '15 at 18:05
  • @Telemachus saw that and was playing with it for a while before asking but while it's clear enough how to define the "n_blank>=2/3/4/5", it's not clear how to go about inverting this limit. – Bolster Dec 02 '15 at 18:09

3 Answers3

8

This one is working well:

:%s/^\n\(^\n\)*/\1/
yolenoyer
  • 8,797
  • 2
  • 27
  • 61
0

Another way would be to use :g. It isn't any faster or better than the :%s solution, but it feels like it is easier to read (at least for me):

:g /^$/ d
0

This might work for you (GNU sed):

sed '/^\n*$/!b;N;//!D' file

This will delete an empty line between two non-empty lines and other empty lines as is, or:

sed '/^\n*$/!b;N;//!D;:a;z;N;//ba' file

As above but this also squeezes multiple empty lines to a single empty line.

potong
  • 55,640
  • 6
  • 51
  • 83