3

I have a text file with following content:

elephant

rhino

giraffe

/* animals who live in Africa */

I would like to add # character at the end of each animal. I can do this with :%s/\n\n/#\r\r/g in vim. However, at first I tried with :%s/\n\n/#\n\n/g and I ended up with:

elephant#^@^@rhino#^@^@giraffe#^@^@/* animals who live in Africa */

Why does vim behave like that? How to understand \n in vim?

6

In the replacement side of vim substitution, a newline is represented by \r. Thus, try:

%s/\n\n/#\r\r/g

The resulting file will look like:

elephant#

rhino# 

giraffe#

/* animals who live in Africa */

In the first half of a substitute command, \n is a newline and \r is a carriage return. By contrast, in the replacement side of the command, \n is a NUL character (hex 00) and \r is a newline.

  • This is the result of an internal storage convention, see :h NL-used-for-Nul and :h CR-used-for-NL. It applies to a number of things, f.i. s/.../.../ and readfile(), but not all. Confusingly, you have to use \n, not \r, in the replacement string in substitute(). Proof: :echo substitute('abc', 'b', "\n", ''). – Satō Katsura Jul 17 '16 at 16:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.