vimtricks.wiki Concise Vim tricks, one at a time.

How do I collapse long runs of blank lines to a single empty line?

Answer

:%s/\n\{3,}/\r\r/g

Explanation

When files pass through formatters, generators, or repeated edits, they often accumulate noisy vertical gaps. Deleting empty lines manually is tedious, and deleting all blank lines usually removes intentional paragraph spacing. This substitution keeps readability by reducing any run of three or more newlines down to exactly two.

How it works

:%s/\n\{3,}/\r\r/g
  • :%s runs substitution across the entire buffer
  • \n\{3,} matches three or more consecutive newline characters
  • \r\r replaces each long run with exactly one blank line (two line breaks)
  • g applies the replacement to every matching run in the file

This gives you a clean, consistent result without flattening sections that should remain visually separated.

Example

Before
alpha




beta



gamma

After
alpha

beta

gamma

Tips

  • If you want zero blank lines between blocks, replace with \r instead
  • If you want to preserve at most two blank lines, change the pattern to \n\{4,} and replacement to \r\r\r
  • Use this as a final cleanup step before committing or exporting text-heavy files

Next

How do I search for 'bar' that is not preceded by 'foo'?