Multifile Operations
From time to time, you may need to perform operations across files. For example, replacing a string across files in a project or iterating across files that threw errors during compilation.
Vim has a simple but very powerful mechanism to perform this kind of operations:
First you have to select the list of files to operate upon:
All buffers.
All the windows of the current tabpage.
The current window of each tabpage.
All files of the quickfix list.
Then run any command of the editor command line over them.
The possibility of combining any list of files with any command provides a great amount of flexibility. For example, may editors provide a way of finding and replacing a string across files. In Vim, you can first find the files and then perform any operation in then, including substituting text.
Operating on buffers, windows and tabpages
To perform an operation across all buffers, windows or the first window of each tabpage, you only have to prefix your command with the corresponding prefix:
:bufdo <command> :windo <command> :tabdo <command>
For example, to replace foo by bar in all buffers, you would execute:
:bufdo %s/foo/bar/g
Or if you want to perform and save the changes at the same time:
:bufdo %s/foo/bar/g | update
An additional example. If you have a macro stored in s, you can execute it in all buffers using:
:bufdo normal S
normal just executes keyboard commands. In this case, S is the command for the execution of the s macro.
Operations over the quickfix list
Executing an action over all the files that appear on the quickfix list is very similar to what you do for buffers, windows and tabpages, only that you use the :cfdo command.
For example, you can populate the quickfix list by searching across files:
:grep -r 'old-string' .
And then replace the used search term —or a different one—, with:
:cfdo %s/old-string/new-string/g | update
One difference with the quickfix list is that the same file can appear multiple times in the results. When you use :cfdo, the command is executed only once per file. However, you can execute an action per each entry in the quickfix list with:
:cdo <command>