vimtricks.wiki Concise Vim tricks, one at a time.

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 (/pattern or the find side of :s/{pattern}/): \n matches the end-of-line character. This lets you find text that spans line boundaries.
  • In a replacement string (the replace side of :s//replacement/): \r inserts a newline, breaking the line at that point. Using \n in 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)
  • \n in a replacement puts a NUL byte visible as ^@ — if you see ^@ appearing, you used \n instead of \r
  • In :substitute, both the search and replace sides follow these rules consistently

Next

How do I quickly evaluate and print a Lua expression in Neovim without calling print()?