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

How do I split a line by inserting a newline with the substitute command?

Answer

:s/,/\r/g

Explanation

In Vim's substitute command, use \r (not \n) in the replacement to insert a real newline. This is one of Vim's most common gotchas: \n in the replacement side inserts a null byte (^@), not a newline. The \r is the correct way to break a line in a substitution.

How it works

The distinction matters only in the replacement string:

  • \n in the pattern — matches a newline character (e.g. in a joined-line search)
  • \r in the replacement — inserts a newline (splits the line)
  • \n in the replacement — inserts a null byte (almost never what you want)

Example

Split a comma-separated list onto separate lines:

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

Result:

apple
banana
cherry

Or split a long function call at each argument:

:%s/,\s*/,\r  /g

This replaces each , with a comma, newline, and two spaces of indentation.

Tips

  • To join lines (opposite direction), use \n in the pattern: :s/\n/ / joins two lines by replacing the newline with a space
  • To split at a fixed column, combine with \%c: :%s/\%81c/\r/g wraps all lines at column 80
  • The \r trick works the same way in :global: :g/pattern/s/,/\r/g

Next

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