How do I run a command on all open buffers at once?
Answer
:bufdo {cmd}
Explanation
:bufdo executes an Ex command in each open buffer in sequence, cycling through every buffer in the buffer list. It is the quickest way to batch-edit all files you currently have open in Vim without touching files on disk that you haven't opened.
How it works
:bufdo {cmd}— switch to each buffer and run{cmd}- Vim visits every listed buffer (those shown in
:ls), runs the command, and moves to the next - Unlisted buffers (e.g., help pages, quickfix windows) are skipped
Common patterns:
" Substitute in all open buffers and save each one
:bufdo %s/foo/bar/ge | update
" Re-indent all open buffers
:bufdo normal gg=G | update
" Remove trailing whitespace everywhere
:bufdo %s/\s\+$//e | update
The e flag on :substitute suppresses the "pattern not found" error when a buffer doesn't contain the pattern. The | update saves only buffers that were actually modified.
Comparison with similar commands
| Command | Scope |
|---|---|
:bufdo |
All listed buffers (currently open in Vim) |
:argdo |
Files in the argument list (vim file1 file2 …) |
:windo |
All windows in the current tab |
:tabdo |
All tabs |
:cdo |
Each entry in the quickfix list |
Tips
- Use
:set hiddenbefore running:bufdoso Vim can switch buffers without requiring each to be saved first. - After running
:bufdo, use:wato write all modified buffers in one command if you prefer not to pipe| update. - To preview without saving, omit
| updateand review diffs with:lsand:b {n}.