Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do I make a replacement with ampersand "&" in vim?

Tags:

vim

vi

As the title says. I want to replace, say "tabs", with the ampersand sign (&).

I use:

:%s/\t/&/g

and of course it doesn't work. I use vim on mac os x (if this makes a difference). Thanks!

like image 695
Arabisch Avatar asked Aug 06 '15 18:08

Arabisch


2 Answers

Are you sure it's the ampersand that's the problem? I got more complaints about the tab. Don't forget to escape it.

:%s/\t/\&/g

like image 114
AlG Avatar answered Sep 23 '22 16:09

AlG


The problem with the ampersand is that it is a regular expression metacharacter for backreferences. The & character in the replacement part of the regular expression means "everything that was matched in the match-part of the expression".

So, for example if you had a file containing the following line:

The quick brown fox jumps over the lazy dog.

Executing a vi command like :s/jumps/a&b/ would result in the following line:

The quick brown fox ajumpsb over the lazy dog.

You can do the same thing using :s/\(jumps\)/a\1b/ but that's a lot more typing.

Why is & useful, other than just an alias for e.g. \1 in a simple match expression? Well, you can also do things like this: :s/lazy \(dog\|cat\)/"&" is now "stupid \1"/:

The quick brown fox jumps over the "lazy dog" is now "stupid dog".

The expression would get very ugly if & were unavailable.

like image 36
Christopher Schultz Avatar answered Sep 22 '22 16:09

Christopher Schultz