Vim - Adding empty line between lines

Other way of doing is:

:%s/$/\r/g

$ is for end of line \r is adding new line g do it globally not just first occurrence

But this will add a line between blank lines too


Vim's :g command is designed for exactly this sort of task; running a single action on every line which matches a particular pattern. Here's my answer:

:g/.\n\n\@!/norm o

The pattern I use is /.\n\n\@!/. Breaking that down into its component pieces:

  • . Matches any character in the line. (used to immediately discard any existing empty lines from consideration)
  • \n Matches a single \n at the end of the character above
  • \n\@! Fails the match if there's another \n immediately after the earlier \n.

(Check :h E59 for more information on \@! and similar match specifiers in regular expressions -- there are a couple others, too!)

So the :g command's regex has now selected every non-empty line which is terminated by a single newline, and which isn't followed by an empty line.

After the pattern in a :g statement comes the command to run on matching lines. In this case, I've told it to execute a normal mode command (abbreviated to norm), and the command to run is simply o, which inserts an empty line below the current line.

So taken together, the command finds every line which doesn't have an empty line beneath it, and adds one. And that's all there is to it! You might like to check the vim wiki's Power of G article for more fancy things you can do with :g (and it's negative sister, :v) -- it's one of those amazingly useful commands which you soon grow to rely on, and then miss terribly in editors which don't have it.