VIM TIPS #3: FuzzyFind and replace
This is just another vim tip that can help you in some cases.
The use case is simple, in your project you have a bunch of file that need to be updated to change just one word or pattern, for example: Update the name of some package that is imported in a lot of files.
Is clear that you have two options:
- Open each file and change the content of it with the corresponding string or
- Search and replace: Search all the files that have that string pattern, and update that string with the correct one in a few steps.
Obviously, we don’t want to spend our time editing file by file, so the option 2 is the one that everyone would choose.
Now, most of the fancy code editors have some option in the menu that allow you to do this, and vim is not less.
How to fuzzy find and replace in vim?
In my case I have fzf installed but you can also do it with just Ag or without any plugin with just `vimgrep`
The whole idea here is run a search for the pattern, this will open the quickfix list, select the items you want and then run a command on the quickfix list to do the replace, like:
First find the files
Then , alt-a
to select the items (if you are using iTerm2 in macOS you need to update the Esc+ config), and enter
to populate the quickfix list with the items selected.
Now, run the command like
:cfdo %s/food/bar/g | :w
cfdo
is a new command available from Vim 7.4+ that allows to run commands over items in the quickfix list natively. (More info about cfdo
)
And voila!. The pattern was updated to the one you need in all the files.