1

Assuming that I have a file containing only of characters and numbers (no special characters or punctuation marks), how can I swap two words that may or may not be right next to each other using VIM?

I tried the following (swap all occurrences of "Tom" with "Jerry") but it doesn't work for obvious reasons.

​:%s/Tom/Jerry/g​ :%s/Jerry/Tom/g

Thank you!

1
  • You may want to check out this SO answer. Mar 23, 2017 at 3:43

2 Answers 2

4

Maybe you could use an intermediary variable like this

​:%s/Tom/XX9G235a65/g​ :%s/Jerry/Tom/g :%s/XX9G235a65/Jerry/g
1
  • Perfect! This worked exactly as I had wanted it. Thank you! Mar 23, 2017 at 16:42
1

Here are two variants (both using :help sub-replace-expression and about equally cumbersome) that use a conditional operator and a Dictionary lookup, respectively:

:substitute/\<\(Tom\|Jerry\)\>/\=submatch(0) ==# 'Tom' ? 'Jerry' : 'Tom'/g
:substitute/\<\(Tom\|Jerry\)\>/\={'Tom':'Jerry', 'Jerry':'Tom'}[submatch(0)]/g

With this, you don't require an intermediate like in @MichaelDurrant's answer.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .