7

I tried to replace '&=' with '=&' in Vim, but the command :%s/&=/=&/g replaced '&=' with '=&='.

Why did that happen ? What command should I use ?

booksee
  • 389
  • 1
  • 3
  • 16

1 Answers1

10

Just escape the ampersand.

:%s/&=/=\&/g

You need to escape it because & is a special character in the replacement that will be replaced with the entire matched pattern.

Bill Lynch
  • 80,138
  • 16
  • 128
  • 173
  • 2
    Can you please explain why you need to escape it? – FDinoff Sep 19 '14 at 02:45
  • 1
    As @sharth just said, `&` is a special character. When used in the replacement side of things `&` is replaced with the entire matched pattern. (In your case, the characters `=&`, giving you the unexpected output: `=&=`) If you want a literal ampersand, just like any special character you have to escape it with a backslash. – Caek Sep 19 '14 at 03:37
  • 1
    @Caek that explanation wasn't there when I posted the comment. (I know what it does) – FDinoff Sep 19 '14 at 03:41