How do I replace the ampersand "&" in vim?

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

I use:

:%s/\t/&/g

      

and of course it won't work. I am using vim for mac os x (if it matters). Thank!

+3


source to share


2 answers


Are you sure there is a problem with the ampersand? I got more complaints about the tab. Remember to avoid this.



:%s/\t/\&/g

+8


source


The problem with the ampersand is that it is a regex 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 have a file containing the following line:

The quick brown fox jumps over the lazy dog.

      

Executing the vi command, for example :s/jumps/a&b/

, will result in the following line:

The quick brown fox ajumpsb over the lazy dog.

      



You can do the same using :s/\(jumps\)/a\1b/

, but this is a lot more printing.

Why is it useful, besides a simple alias, such \1

as a simple coincidence? 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 will be very ugly if &

not available.

0


source







All Articles