Review Replacements in Vim

4.7
(69)

Substitutions, Vim’s find-and-replace, are a heavily used Vim feature with many variations and options. We’ve written often of substitutions already, including using the /c flag to confirm substitutions before they happen.

There’s another useful approach when performing a number of substitutions within a file. Confirming each one can be tedious. But what if we still want to review them at a glance to make sure no erroneous substitutions were made?

We can use Vim’s global command, :g, which invokes Ex commands across a range:

:g/MATCH/#|s/MATCH/REPLACE/g|#

In the command above, we replace all instances of MATCH with REPLACE. But while doing so, we print out the line number and the actual line that matches the text. And then we print out the same but after the substitution is made. The result is something like this, giving us an at-a-glance view of all the changes we just made:

:g/MATCH/#|s/MATCH/REPLACE/g|#
10 this text will MATCH
10 this text will REPLACE
28 Excuse me, do you have any MATCHES?
28 Excuse me, do you have any REPLACEES?

Watch the video below to see this in action.

If you have any other great tips, we’d love to hear about them. Email us!

How useful was this tip?

Average rating 4.7 / 5. Vote count: 69

No votes so far! Be the first to rate this tip.

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Written by

Colin Bartlett

105 Posts

Vim enthusiast and software developer for more than 20 years.
View all posts