这是我将使用的完整命令序列:
/stringiwanttoreplace
:vimgrep /<c-r>// **
:Qargs
:argdo %s//newstring/g
:argdo update
在第一行中,我们搜索目标模式。这填充了最后一个搜索模式寄存器(:help quote/ http://vimdoc.sourceforge.net/htmldoc/change.html#quote_),这意味着我们不必再次完整地输入它。
The :vimgrep
command searches the entire project for the specified pattern. Type <c-r>/
as ctlr+r followed by / - this inserts the contents of the last search pattern register onto the command line. The first and last /
symbols are delimiters for the search field. The trailing **
tells Vim to look inside every file and directory below the current directory.
此时,快速修复列表将填充所有匹配文件中的搜索匹配项。:Qargs
是一个自定义命令,它使用快速修复列表中列出的所有文件填充参数列表。这是实现:
command! -nargs=0 -bar Qargs execute 'args ' . QuickfixFilenames()
function! QuickfixFilenames()
" Building a hash ensures we get each buffer only once
let buffer_numbers = {}
for quickfix_item in getqflist()
let buffer_numbers[quickfix_item['bufnr']] = bufname(quickfix_item['bufnr'])
endfor
return join(values(buffer_numbers))
endfunction
将其添加到您的vimrc
file.
跑完后:Qargs
,我们的参数列表现在应该包含包含目标字符串的所有文件。所以我们可以运行替换命令:argdo
,执行每个文件中的命令。我们可以将替换命令的搜索字段留空,它会自动使用最新的搜索模式。如果您愿意,您可以包括c
运行替换命令时标记,然后系统会提示您确认。
最后,:argdo update
命令保存更改的每个文件。
As @彼得·林克 https://stackoverflow.com/users/438329/peter-rincker指出,你应该确保 Vim 的'hidden' http://vimdoc.sourceforge.net/htmldoc/options.html#'hidden'选项已启用,否则当您在将任何更改写入活动缓冲区之前尝试切换到另一个缓冲区时,将会引发错误。
另请注意,最后 3 个命令可以在单个命令行中执行,方法是用竖线字符分隔它们。
:Qargs | argdo %s//replacement/gc | update
The :Qargs
命令是从这个答案 https://stackoverflow.com/questions/5686206/search-replace-using-quickfix-list-in-vim/5686810#5686810(由我),这反过来又受到启发这个答案 https://stackoverflow.com/questions/4792561/how-to-do-search-replace-with-ack-in-vim/4793316#4793316 by DrAl https://stackoverflow.com/users/72791/dral。一个非常类似的解决方案 https://stackoverflow.com/questions/1830839/how-to-open-multiple-files-in-vim-after-vimgrep/6888929#6888929发布者:@ib https://stackoverflow.com/users/254635/ib,这对我来说意味着 Vim 应该真正实现类似的东西:quickfixdo
原生地。