Interactive replace across files
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”. Thec
flag forces us to confirm each one and theupdate
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.