Tip 96: Find and Replace Across Multiple Files
Return to the top: <<Practical Vim>>
Example: find and replace to change each occurrence of "Pragmatic Vim" to "Practical Vim" in each txt file.
The Substitute Command
/Pragmatic\ze Vim :%s//Practical/g
Execute a Substitute Command on All Files in the Current Project
:args **/*.txt :set hidden :argdo %s//Practical/ge
Build a List of Files Containing Our Target Pattern
/Pragmatic\ze Vim :vimgrep /<C-r>// **/*.txt
-
Each match returned by vimgrep is recorded in the quickfix list, and we can browse the results by running
:copen
, which opens the quickfix window. -
qargs.vim
command! -nargs=0 -bar Qargs execute 'args' QuickfixFilenames() function! QuickfixFilenames() let buffer_numbers = {} for quickfix_item in getqflist() let buffer_numbers[quickfix_item['bufnr']] = bufname(quickfix_item['bufnr']) endfor return join(map(values(buffer_numbers), 'fnameescape(v:val)')) endfunction
-
using qargs.vim
/Pragmatic\ze Vim :vimgrep /<C-r>// **/*.txt :Qargs :argdo %s//Practical/g :argdo update
-
:update
saves the file, but only if it has been changed
-
using qargs.vim
References:
# If you open the file in vim, # then you can \"ayy@a the next line to execute the vim command: :h update
-
the last three commands could be combined into one
:Qargs | argdo %s//Practical/g | update
-
On Vim’s command line,
|
simply stands for a command separator, making it equivalent to the semicolon in the Unix shell.
-
On Vim’s command line,
References:
# If you open the file in vim, # then you can \"ayy@a the next line to execute the vim command: :h :bar