Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace a character by a newline in Vim

I'm trying to replace each , in the current file by a new line:

:%s/,/\n/g  

But it inserts what looks like a ^@ instead of an actual newline. The file is not in DOS mode or anything.

What should I do?

If you are curious, like me, check the question Why is \r a newline for Vim? as well.

like image 721
Vinko Vrsalovic Avatar asked Sep 16 '08 11:09

Vinko Vrsalovic


People also ask

How do you replace letters in Vim?

The simplest way to perform a search and replace in Vim editor is using the slash and dot method. We can use the slash to search for a word, and then use the dot to replace it. This will highlight the first occurrence of the word “article”, and we can press the Enter key to jump to it.

How do I replace a character in vi?

Position the cursor over the character and type r , followed by just one replacement character. After the substitution, vi automatically returns to command mode (you do not need to press Esc).


2 Answers

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. This asymmetry is due to the fact that \n and \r do slightly different things:

\n matches an end of line (newline), whereas \r matches a carriage return. On the other hand, in substitutions \n inserts a null character whereas \r inserts a newline (more precisely, it’s treated as the input CR). Here’s a small, non-interactive example to illustrate this, using the Vim command line feature (in other words, you can copy and paste the following into a terminal to run it). xxd shows a hexdump of the resulting file.

echo bar > test (echo 'Before:'; xxd test) > output.txt vim test '+s/b/\n/' '+s/a/\r/' +wq (echo 'After:'; xxd test) >> output.txt more output.txt 
Before: 0000000: 6261 720a                                bar. After: 0000000: 000a 720a                                ..r. 

In other words, \n has inserted the byte 0x00 into the text; \r has inserted the byte 0x0a.

like image 163
Konrad Rudolph Avatar answered Oct 13 '22 23:10

Konrad Rudolph


Here's the trick:

First, set your Vi(m) session to allow pattern matching with special characters (i.e.: newline). It's probably worth putting this line in your .vimrc or .exrc file:

:set magic 

Next, do:

:s/,/,^M/g 

To get the ^M character, type Ctrl + V and hit Enter. Under Windows, do Ctrl + Q, Enter. The only way I can remember these is by remembering how little sense they make:

A: What would be the worst control-character to use to represent a newline?

B: Either q (because it usually means "Quit") or v because it would be so easy to type Ctrl + C by mistake and kill the editor.

A: Make it so.

like image 36
Logan Avatar answered Oct 14 '22 01:10

Logan