How do I insert an actual newline in a substitution replacement, and why does backslash-n not work?
Answer
s/pattern/\r/
Explanation
In Vim substitutions, \r in the replacement string inserts a line break, creating a new line. Many users try \n instead, which is surprising: in the replacement, \n inserts a literal NUL byte (displayed as ^@) rather than a line break. This is one of Vim's most common regex gotchas.
How it works
The asymmetry between the two sides of a substitution:
- Search pattern (left side):
\nmatches a newline in the buffer - Replacement string (right side):
\rinserts a line break;\ninserts a NUL character
This is counterintuitive because most tools use \n consistently for newlines. Vim's internal line representation is the source of this distinction.
Example
Split a comma-separated list onto separate lines:
apple,banana,cherry
Run:
:%s/,/\r/g
Result:
apple
banana
cherry
Tips
- The reverse (joining lines) uses
\nin the search side correctly::%s/\n/,/gjoins all lines with commas - To insert a newline before a matched word:
:s/\<TODO\>/\r&/g—&expands to the whole match,\rprepends a newline - To break a long line at each comma and keep the comma:
:s/,/,\r/g - In Neovim and recent Vim,
\nin the replacement may work on some platforms as a line break, but\ris the portable and reliable choice for all Vim versions