Tip 96Swap Two or More Words

We can devise a substitute command that swaps all occurrences of one word with another and vice versa by using the expression register and a Vim script dictionary.

Take this excerpt:

 The dog bit the man.

Suppose that we want to swap the order of the words “dog” and “man.” We could, of course, use a succession of yank and put operations, as demonstrated in Swap Two Words. But let’s consider how we would go about doing this with the substitute command.

Here’s a naïve attempt at a solution:

=> :%s/dog/man/g
=> :%s/man/dog/g

The first command replaces the word “dog” with “man,” leaving us with the phrase “the man bit the man.” Then the second command replaces both occurrences ...

Get Practical Vim, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.