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.
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.
The command is usually a simple search and replace and looks like this:
The following command line is an example of the substitution command
%s to replace all occurrences of
g (everywhere, in all lines of the current buffer). The whole command line however will be run on all buffers and thus change
bar in all buffered files.
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
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
bar and all occurrences of
g (everywhere, in all lines of the current buffer). The whole command line will run on all buffers.
Explanations of Vim commands used in this document.
- Run a command in multiple buffers
- Search and replace all lines in the buffer that match the pattern.
- Change all occurrences in each line (globally) of the buffer.
- Command separator