Vim: Edit multiple files at the same time
How to edit multiple files in the buffer of the Vim text editor, following a certain search and replace (substitution) pattern, at the same time.
To edit multiple files in the Vim text editor [1] at the same time, you must first open the files you want to edit, so they are associated with a buffer.
A buffer is a file loaded into memory for editing. An instance of Vim can contain multiple buffers. Windows and tab pages can, to some degree, be considered visual presentations of the buffers. They are both abstraction layers of buffers.
Changes in all files in the buffer can then be done with the bufdo
command, which allows to run a command in multiple buffers.
Generic syntax
The command is usually a simple search and replace and looks like this:
:bufdo %s/pattern/replace/g
Single change
The following command line is an example of the substitution command %s
to replace all occurrences of foo
with bar
globally g
(everywhere, in all lines of the current buffer). The whole command line however will be run on all buffers and thus change foo
to bar
in all buffered files.
:bufdo %s/foo/bar/g
After running the command line, changes are not automatically saved. In Vim you can save changes in all buffers with :wa
(write all). Alternatively you can adjust the command line to automatically save
Multiple changes
To run multiple substitution commands at once, you can chain them using the pipe |
as a command separator like this:
:bufdo %s/foo/bar/g | %s/baz/qux/g
This line will replace all occurrences of foo
with bar
and all occurrences of baz
with qux
globally g
(everywhere, in all lines of the current buffer). The whole command line will run on all buffers.
Commands
Explanations of Vim commands used in this document.
:bufdo
- Run a command in multiple buffers
%s
- Search and replace all lines in the buffer that match the pattern.
g
- Change all occurrences in each line (globally) of the buffer.
|
- Command separator