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:
\nin the pattern — matches a newline character (e.g. in a joined-line search)\rin the replacement — inserts a newline (splits the line)\nin 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
\nin 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/gwraps all lines at column 80 - The
\rtrick works the same way in:global::g/pattern/s/,/\r/g