A vim “delete blank lines” command

vim FAQ: How do I delete blank lines in vim?

To delete blank lines in vim (empty lines), use this vim command in “last line mode”:

:g/^$/d

Here’s a brief explanation of how this vim “delete blank lines” command works:

  • The : character says, “put vim in last-line mode.”
  • The g character says, “perform the following operation globally in this file.” (Operate on all lines in this file.)
  • The forward slash characters enclose the pattern I’m trying to match. In this case I want to match blank lines, so I use the regular expression ^$. Here the ^ means “beginning of line,” and $ means “end of line,” so with no characters in between them, this vim regex means “blank line.” (If I had typed ^abc$, that would mean, “find a line with only the sequence of characters ‘abc’”.)
  • The d at the end of the command says, “When you find this pattern, delete the line.”

I hope this vim “delete blank lines” command example is helpful. If you know of a simpler way to delete blank lines in vim, please leave a comment below.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.