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

How do I delete all blank and whitespace-only lines from a file in Vim?

Answer

:g/^\s*$/d

Explanation

The global command :g/^\s*$/d removes every line that is empty or contains only whitespace — a common cleanup task when tidying up code, configuration files, or pasted content.

How it works

  • :g — run the following command on every line where the pattern matches
  • /^\s*$/ — matches lines that start (^) and end ($) with zero or more whitespace characters (\s*), meaning the entire line is blank or spaces/tabs
  • d — delete those lines

This differs from :g/^$/d, which only removes lines that are completely empty (zero characters), leaving lines with spaces or tabs intact.

Example

Before:

foo

bar
   
baz
	

After :g/^\s*$/d:

foo
bar
baz

Tips

  • To delete only truly empty lines (no spaces): :g/^$/d
  • To delete blank lines in a range: :{start},{end}g/^\s*$/d
  • To squeeze multiple consecutive blank lines into one (like cat -s), use: :g/^\s*$\n\s*$/d
  • Combine with visual selection: :'<,'>g/^\s*$/d

Next

How do I quickly evaluate and print a Lua expression in Neovim without calling print()?