What is the difference between \n and \r in Vim search patterns versus substitution replacements?
Answer
\n in search, \r in replacement
Explanation
Vim uses \n and \r differently depending on whether they appear in a search pattern or a replacement string, and mixing them up is a common source of confusion.
How it works
- In a search pattern (
/patternor the find side of:s/{pattern}/):\nmatches the end-of-line character. This lets you find text that spans line boundaries. - In a replacement string (the replace side of
:s//replacement/):\rinserts a newline, breaking the line at that point. Using\nin the replacement inserts a literal NUL character (^@), which is almost never what you want.
The asymmetry exists because internally Vim stores line separators differently than most tools.
Example
Join the current line with the next by replacing the newline:
:s/\n/ /
Split a comma-separated list onto separate lines:
:%s/,/,\r/g
Before:
foo,bar,baz
After:
foo,
bar,
baz
Tips
- Mnemonic: search for
\n(newline), replace with\r(return = new line) \nin a replacement puts a NUL byte visible as^@— if you see^@appearing, you used\ninstead of\r- In
:substitute, both the search and replace sides follow these rules consistently