Interactive replace across files

4.9
(40)

We’ve covered substitution many times simply because there are numerous useful hidden corners around pattern substitution in Vim. Learning them all will help improve your efficiency and give you flexible options for varying scenarios.

In this tip, we’ll combine two Vim features into a trick that lets you find and replace across all files in your project, interactively. Vim will stop at each pattern match and allow you to replace it or skip it — exactly how the Find and Replace feature of modern IDEs and other editors works. Here’s how we do it:

First, load your quickfix list with a list of matches to a given pattern. How? I use :Ggrep which comes from Fugitive, but you could use native :grep or another plugin like :Ack:

Next, run a command across all the results in the quickfix list with cdo. The cdo command will run a command on every single line in the quickfix list. It’s cousin, cfdo, will run a command on every unique file in the quickfix list. In this example, we’ll use the former.

There’s an example in the video below. Here’s what I’m doing:

  • :Ggrep Checks – Finds all the references in the project to Checks, and load them into the quickfix list
  • :cdo s/Checks/Balances/gc | update – Iterates over every result from the quickfix list and replaces all the references to “Checks” on the line with “Balances”. The c flag forces us to confirm each one and the update command writes the buffer after each.

Now we can press y or n to replace or skip. For more details on all the options available, see our post about how to confirm replacements.

How useful was this tip?

Average rating 4.9 / 5. Vote count: 40

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

92 Posts

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

1 thought on “Interactive replace across files”

Leave a reply

Your email address will not be published. Required fields are marked *