Jason McGhee
Jason McGhee

Reputation: 103

Vim replace two words with one another

How would one replace all instances of 'foo' with 'bar' and 'bar' with 'foo' in vim?

Upvotes: 9

Views: 2352

Answers (4)

kev
kev

Reputation: 161674

Take a look at this: how to write only one pattern to exchange two strings in two-ways in vim

:s/foo\|bar/\={'foo':'bar','bar':'foo'}[submatch(0)]/g

Upvotes: 13

jcollado
jcollado

Reputation: 40384

Aside from using a temporary word for the change, you could also use abolish plugin like this:

:%SubVert/{foo,bar}/{bar,foo}/g

Upvotes: 8

core1024
core1024

Reputation: 1882

You can do it using temp word. Just be sure that it doesn't exists in the current document.

/\<asd123\>
:%s/\<foo\>/asd123/g
:%s/\<asd123\>/bar/g
:%s/\<bar\>/foo/g

Upvotes: 0

Adrien BARRAL
Adrien BARRAL

Reputation: 3604

  1. :%s/foo/bbaarr/g
  2. :%s/bar/foo/g
  3. :%s/bbaarr/foo/g

It must exist an smartest way to do it, but this one will work for sure !

Upvotes: 1

Related Questions