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

What is the difference between \n and \r in Vim substitution patterns and replacements?

Answer

:s/\n/ /

Explanation

One of the most confusing asymmetries in Vim's substitution syntax: \n and \r mean different things depending on whether they appear in the pattern or the replacement. Getting this wrong silently produces wrong results with no error message.

How it works

In the search pattern:

  • \n — matches a real newline character (line break in the buffer)
  • \r — matches a carriage return (<CR>, 0x0D), rarely useful

In the replacement string:

  • \r — inserts a newline (splits the line at this point)
  • \n — inserts a null byte (NUL, 0x00), almost never what you want

So the rule is: use \n to find line breaks, use \r to create them.

Example

Join two lines by replacing the newline between them with a space:

Before:
foo
bar
:s/\n/ /
After:
foo bar

Split a comma-separated line into multiple lines:

:s/,/\r/g
Before: a,b,c
After:
a
b
c

Tips

  • :%s/\n/\r/g (replace every newline with \r) is a no-op — it just replaces each newline with another newline.
  • To join all lines into one: :%j or :%s/\n/ /g.
  • On Windows files with DOS line endings, \r\n in the pattern matches the <CR><LF> pair.

Next

How do I make Vim show error messages that are silently swallowed inside :silent! or :try blocks?