vimtricks.wiki Concise Vim tricks, one at a time.

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 of old with new in the entire file; the e flag suppresses errors when no match is found in a particular line
  • | update — save the file only if it was modified (unlike :w which 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 :cdo instead when you need to operate on each individual quickfix entry rather than each file
  • Pair with :vimgrep or an external grep (:grep) to populate the quickfix list before running :cfdo
  • Add c to the substitute flags (gce) to confirm each replacement interactively
  • Use :cfdo undo | update to revert all changes if something goes wrong

Next

How do I return to normal mode from absolutely any mode in Vim?