How do I replace a character or pattern with a newline in a substitute command?
Answer
:%s/,/\r/g
Explanation
In Vim's substitute command, \r in the replacement string inserts a newline. This is different from \n which works in the search pattern but inserts a null byte in the replacement. This distinction trips up many users.
The key rule
| Context | Newline |
|---|---|
| Search pattern | \n matches a newline |
| Replacement string | \r inserts a newline |
Examples
" Split comma-separated values onto separate lines
:%s/,/\r/g
" Split on semicolons
:%s/;/\r/g
" Add a blank line after each period-space
:%s/\. /\.\r\r/g
" Break a long HTML tag onto multiple lines
:%s/ \(\w\+=\)/\r \1/g
Before/After
Before :%s/,/\r/g:
apple,banana,cherry,date
After:
apple
banana
cherry
date
The opposite: join lines
" Replace newlines with commas (join lines)
:%s/\n/,/g
Here \n works in the search pattern to find newlines.
Tips
- Remember:
\nin search,\rin replacement — this is one of Vim's most confusing quirks - Using
\nin the replacement inserts a null byte (^@), not a newline \ris a carriage return that Vim interprets as a line break in the replacement- This works identically in Vim and Neovim
- Documented under
:help sub-replace-special