In vim editor, I want to replace a newline character (\n) with two new line characters (\n\n) using vim command mode.
Input file content:
This is my first line.
This is second line.
Command that I tried:
:%s/\n/\n\n/g
it replaces the string with unwanted characters as
This is my first line.^@^@This is second line.^@^@
Then I tried the following command
:%s/\n/\r\r/g
It is working properly. Can you explain why it is working fine with second command?
Best Answer
Oddly enough,
\n
in vim for replacement does not mean newline, but null. ASCII nul is^@
(Ctrl+@).Historically, vi replaces
^M
(Ctrl+M) as the line-ending, which is the newline. vim added an extension\r
(like the C language) to mean the same as^M
, but the developers chose to make\n
mean null when replacing text. This is inconsistent with its use in searches, which find a newline.Further reading:
\n