Bolster
Bolster

Reputation: 7916

Vim / Sed: Delete Only Single Blank Lines

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

Upvotes: 2

Views: 417

Answers (3)

potong
potong

Reputation: 58578

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.

Upvotes: 0

bsellersful
bsellersful

Reputation: 45

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

Upvotes: 0

yolenoyer
yolenoyer

Reputation: 9465

This one is working well:

:%s/^\n\(^\n\)*/\1/

Upvotes: 8

Related Questions