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

How do I replace text with a newline in a substitute command?

Answer

:%s/pattern/\r/g

Explanation

In the replacement part of :s, \r inserts a newline. Note that this is different from the search pattern, where \n matches a newline.

How it works

  • In the search pattern: \n matches a newline
  • In the replacement: \r inserts a newline
  • This asymmetry is a common source of confusion

Example

Split comma-separated values onto separate lines:

:%s/,/\r/g

Before: a,b,c,d After:

a
b
c
d

Tips

  • \n in the replacement inserts a null character (not a newline)
  • \r in the replacement is always a newline
  • \n in the search is always a newline
  • This is consistent with how Vim stores newlines internally

Next

How do you yank a single word into a named register?