Replacing Multiple blank lines with a single blank line in vim / sed

regular expressionsedvim

Question more or less says it all. I'm aware that /^$/d will remove all blank lines, but I can't see how to say 'replace two or more blank lines with a single blank line'

Any ideas?

Best Answer

If you aren't firing vim or sed for some other use, cat actually has an easy builtin way to collapse multiple blank lines, just use cat -s.

If you were already in vim and wanted to stay there, you could do this with the internal search and replace by issuing: :%s!\n\n\n\+!^M^M!g (The ^M is the visual representation of a newline, you can enter it by hitting Ctrl+vEnter), or save yourself the typing by just shelling out to cat: :%!cat -s.

Related Question