Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Put Newline Characters in Substitutions of Regular Expressions of GVim

I use GVim on Windows 7.

I want to learn how to put newline characters by using regex substitutions. To do this I try to use \r and \n metacharacters but the substituted text doesn't show normal newlines.

For example, at the beginning I have:

line 1
line 2

Before substitution

I use the following substitution expression:

:%s/\n/\n\n/g

Then GVim produces the following text:

line 1^@^@line 2^@^@

After substitution with \n as newline characters

Instead, if I use \r\n in the substitution expression

:%s/\n/\r\n/g

Then GVim produces the following text:

line 1
^@line 2
^@

After substitution with \r\n as newline

What are those ^@ characters?

How to use newline characters in the substitution expression properly?

like image 342
Mert Nuhoglu Avatar asked May 03 '11 19:05

Mert Nuhoglu


People also ask

How do you represent a new line in regex?

"\n" matches a newline character.

How do I create a new line character in Vim?

Use \r instead of \n . Substituting by \n inserts a null character into the text. To get a newline, use \r . When searching for a newline, you'd still use \n , however.


2 Answers

^@ is a nul


For some reason, vim wants to see \r in the replacement text in order to insert a newline. (\n in the replacement inserts a nul.)

So, after succesfully locating newlines by running /\n, try:

s//\r/

Or to add an extra newline:

s/$/\r/

On the pattern side, \r means an actual (015) CR character, leading to the following strange-looking command when you want to replace returns with newlines:

s/\r/\r/

No, it's not a no-op.

like image 197
DigitalRoss Avatar answered Oct 19 '22 01:10

DigitalRoss


This

s/\r/\r/

fails. But

s/\n/\r/

works fine.

like image 37
Aaron Avatar answered Oct 19 '22 02:10

Aaron