Let's say that I have a file containing several occurrences of the word foo
and several
occurrences of the word bar
.
I need to make all the words foo
become bar
and inversely all the words
bar
become foo
.
What is the most efficient way to do that?
My first thought was to make it 3 steps:
- First make
bar
become something temporary:%s/bar/barTEMP/g
- Then make
foo
becomebar
::%s/foo/bar/g
- Finally substitute
barTEMP
::%s/barTEMP/foo/g
It is an implementation of a classical algorithm to switch the value of two variables but is there a more efficient way to do this?
I know I can write a function to do the 3 substitutions for me but
what I'm wondering is if there is a different method than using a temporary
substitution. For example I was thinking maybe something could be done by using
an |
in the search pattern:
:%s/\(foo\|bar\)/???/g
But that would require to make the replacement string change depending on the actually matched word and I don't know how to do that. (Note that this idea is just an example, if someone come up with something better that would be nice too)
:%S/{foo,bar}/{bar,foo}/g
. This works well as long as you don't want to match only whole words.:h expr1
), though using a dictionary is obviously better for >2 words.