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\nin the search pattern matches a newline (line break)\rin the replacement inserts a newline\nin the replacement inserts aNULcharacter (^@) — 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),\rstill means newline in the replacement — the magic mode only affects the search pattern