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

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.


Use \n to indicate a newline in the search pattern. Use Ctrl+M in the replacement text, or a backreference. See :help pattern and :help sub-replace-special (linked from :help :s).

%s/\(\n\n\)\n\+/\1/

If in Vim, just do this:

:%!cat -s

The -s flag for cat squeezes multiple blank lines into one.