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

How do I run a quickfix refactor once per file instead of once per match?

Answer

:cfdo %s/\<GetUser\>/FetchUser/ge | update

Explanation

When quickfix has many matches per file, :cdo can execute your command repeatedly in the same buffer. That can be slow and occasionally surprising if your command is not idempotent. :cfdo is the safer choice when the operation should run once per file, such as a full-buffer substitution followed by :update.

How it works

  • :cfdo iterates over each file represented in quickfix, not each individual match row
  • %s/\<GetUser\>/FetchUser/ge performs a whole-buffer substitution in that file
  • \< and \> keep the replacement to whole words only
  • e suppresses "pattern not found" errors so the loop continues cleanly
  • | update writes only if the buffer changed, which avoids unnecessary disk writes

Example

Suppose quickfix was built from a project search and contains 120 entries across 9 files.

With :cdo  -> command may run up to 120 times
With :cfdo -> command runs exactly 9 times

For file-scoped edits, :cfdo is usually the right granularity.

Tips

  • Use :cdo when you truly need match-by-match context-sensitive edits.
  • Combine :vimgrep + :cfdo for a full in-editor refactor loop with explicit review.

Next

How do I remove trailing spaces only within the currently selected visual block?