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

How do I insert a newline in the replacement string of a :s substitution?

Answer

:s/,/,\r/g

Explanation

In Vim's :substitute command, \r in the replacement string inserts a literal newline — it splits the line at that point. This trips up many Vim users because \n is used to match a newline in the search pattern, but \n in the replacement inserts a null byte (NUL), not a newline. For replacements, \r is what you want.

How it works

  • :s/pattern/\r/ — replaces the match with a newline, splitting the line
  • \n in the search pattern matches a newline (line break)
  • \r in the replacement inserts a newline
  • \n in the replacement inserts a NUL character (^@) — almost certainly not what you want

Example

Split a comma-separated list onto separate lines:

Before: apple,banana,cherry
:s/,/,\r/g
After:
apple,
banana,
cherry

Or replace the comma with a newline entirely:

:s/, /\r/g
After:
apple
banana
cherry

Tips

  • This works the same in the global command: :g/pattern/s/old/\r/
  • To join lines (the reverse), search for the newline with \n: :s/\n/ / joins the current line with the next
  • In very magic mode (\v), \r still means newline in the replacement — the magic mode only affects the search pattern

Next

How do I match a pattern only when it is preceded or followed by another pattern, without including that context in the match?