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
Next, run a command across all the results in the quickfix list with
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
cflag forces us to confirm each one and the
updatecommand writes the buffer after each.
Now we can press
n to replace or skip. For more details on all the options available, see our post about how to confirm replacements.
We are sorry that this post was not useful for you!
Let us improve this post!
Tell us how we can improve this post?