How do I run the same command across all open buffers at once?
Answer
:bufdo
Explanation
When you need to apply the same change to every file you have open in Vim, switching to each buffer manually is tedious and error-prone. The :bufdo command iterates over every buffer in your buffer list and executes a given command in each one, making bulk edits fast and reliable.
How it works
:bufdo {cmd}— execute{cmd}in every listed buffer- Vim switches to each buffer sequentially, runs the command, then moves to the next
- Combine with
| updateto save each buffer after the change
A common pattern is :bufdo %s/old/new/ge | update — this replaces old with new in every open buffer and writes each file. The e flag prevents errors when a buffer has no matches.
Example
You have three files open and want to replace all instances of var with const:
:bufdo %s/\<var\>/const/ge | update
This visits each buffer, performs the substitution, and saves:
Buffer 1 (app.js): var x = 1; → const x = 1;
Buffer 2 (utils.js): var y = 2; → const y = 2;
Buffer 3 (test.js): var z = 3; → const z = 3;
Tips
- Use
:bufdowith any Ex command — for example,:bufdo set expandtab | retab | updateto convert tabs to spaces in all buffers :argdois the equivalent for the argument list, and:windofor visible windows- Add
| updateto auto-save, or omit it to review changes before writing - Use
:set hiddenif you get errors about unsaved buffers when switching