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:
\nmatches a newline - In the replacement:
\rinserts 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
\nin the replacement inserts a null character (not a newline)\rin the replacement is always a newline\nin the search is always a newline- This is consistent with how Vim stores newlines internally