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
:gis 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 betweendis 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/das an alternative — it deletes every line that does not contain a non-whitespace character, achieving the same result - Use
:g/^$/dwithin a range to only affect part of the file::10,50g/^$/dremoves blank lines between lines 10 and 50 - Use
:%s/\n\{3,}/\r\r/gto collapse multiple consecutive blank lines into a single blank line instead of removing them all - Combine with undo — press
uimmediately if the result is not what you expected - Use
:g/^\s*$/dwhen working with files that have trailing whitespace on otherwise empty lines