Vim Command to Delete Empty Lines

:v/\S/d


This is a neat little command.

We're executing "delete" on every line that does not match any non-whitespace character (i.e. \S).


The Power of Multi-Repeat in Command-Line-Mode

As we’ve seen time and again, vim provides an elegant solution to a complicated problem by allowing us to build a complex action from simple commands.

First, lets break this command down into its component actions: : v /\S/ d

We start off using : to get us into command-line-mode.

Next, we issue our first command in command-line-mode: v. v is special class of command called a multi-repeat because it executes the given command on multiple lines. The most common multi-repeat is s which executes a command on all lines that match the given regular expression. v, on the other hand, executes the command on all lines that do not match the pattern.

Now for the regular expression /\S/. The leading and trailing forward-slash demarcates the begining and end of the match patter. We are using \S which will match any non-whitespace character (i.e. any non-empty line). So, we have a pattern which matches every non-empty line and a multi-repeat to execute a command on every line that does not match that pattern.

All that’s left is to delete the matched lines with the delete line command: d.

Parting Thoughts

The trick to this command is rephrasing the problem from “delete all empty lines” to “delete all lines that do not have any text in them.” Trying to program the first problem statement would give us something like: :g/^\s*$/d. Here we use another multi-command :g to execute the command on every line that does match the regular expression. But, look at how much uglier ^\s*$ is than \S. It also took me longer than I’m willing to admit to figure out the correct regular expression 😜