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

How do I delete all blank lines in a file?

Answer

:g/^$/d

Explanation

The :g/^$/d command deletes every blank line in the file using Vim's powerful global command. It is one of the most commonly used :g patterns and is invaluable for cleaning up files with excessive whitespace.

How it works

  • :g is the global command — it executes an action on every line matching a pattern
  • /^$/ is a regex that matches blank lines: ^ is the start of the line and $ is the end, with nothing in between
  • d is the delete command applied to each matching line

Example

Given the text:

first line

second line


third line

Running :g/^$/d results in:

first line
second line
third line

All blank lines are removed, leaving only lines with content.

Variations

Delete lines that are blank or contain only whitespace:

:g/^\s*$/d

The \s* matches zero or more whitespace characters (spaces, tabs), so lines that appear empty but contain hidden whitespace are also removed.

Tips

  • Use :v/\S/d as an alternative — it deletes every line that does not contain a non-whitespace character, achieving the same result
  • Use :g/^$/d within a range to only affect part of the file: :10,50g/^$/d removes blank lines between lines 10 and 50
  • Use :%s/\n\{3,}/\r\r/g to collapse multiple consecutive blank lines into a single blank line instead of removing them all
  • Combine with undo — press u immediately if the result is not what you expected
  • Use :g/^\s*$/d when working with files that have trailing whitespace on otherwise empty lines

Next

How do I edit multiple lines at once using multiple cursors in Vim?