How do I run a substitute command on every file in the quickfix list at once?
Answer
:cfdo %s/old/new/ge | update
Explanation
When you grep across your project and want to perform a search-and-replace on every file that matched, :cfdo is the most efficient approach. Unlike :cdo which runs once per quickfix entry, :cfdo runs once per unique file in the quickfix list, avoiding redundant processing when a file has multiple matches.
How it works
:cfdo— execute a command once for each unique file in the quickfix list%s/old/new/ge— substitute all occurrences ofoldwithnewin the entire file; theeflag suppresses errors when no match is found in a particular line| update— save the file only if it was modified (unlike:wwhich writes unconditionally)
Example
Suppose you want to rename a function across your project:
:vimgrep /calculateTotal/g **/*.js
:cfdo %s/calculateTotal/computeTotal/ge | update
The first command populates the quickfix list with all files containing calculateTotal. The second command performs the replacement in each file and saves it.
Tips
- Use
:cdoinstead when you need to operate on each individual quickfix entry rather than each file - Pair with
:vimgrepor an external grep (:grep) to populate the quickfix list before running:cfdo - Add
cto the substitute flags (gce) to confirm each replacement interactively - Use
:cfdo undo | updateto revert all changes if something goes wrong