Search and replace in Vim across all the project files

后端 未结 11 1907
我寻月下人不归
我寻月下人不归 2020-12-07 07:00

I\'m looking for the best way to do search-and-replace (with confirmation) across all project files in Vim. By \"project files\" I mean files in the current directory, some

11条回答
  •  旧时难觅i
    2020-12-07 07:37

    Populate :args from a shell command

    It's possible (on some operating systems1)) to supply the files for :args via a shell command.

    For example, if you have ack2 installed,

    :args `ack -l pattern`
    

    will ask ack to return a list of files containing 'pattern' and put these on the argument list.

    Or with plain ol' grep i guess it'd be:

    :args `grep -lr pattern .`  
    


    You can then just use :argdo as described by the OP:

    :argdo %s/pattern/replacement/gce
    


    Populate :args from the quickfix list

    Also check out nelstrom's answer to a related question describing a simple user defined command that populates the arglist from the current quickfix list. This works great with many commands and plugins whose output ends up in the quickfix list (:vimgrep, :Ack3, :Ggrep4).

    The sequence to perform a project wide search could then be done with:

    :vimgrep /pattern/ **/*
    :Qargs 
    :argdo %s/findme/replacement/gc
    

    where :Qargs is the call to the user defined command that populates the arglist from the quickfix list.

    You'll also find links in the ensuing discussion to simple plugins that get this workflow down to 2 or 3 commands.

    Links

    1. :h {arglist} - vimdoc.sourceforge.net/htmldoc/editing.html#{arglist}
    2. ack - betterthangrep.com/
    3. ack.vim - github.com/mileszs/ack.vim
    4. fugitive - github.com/tpope/vim-fugitive

提交回复
热议问题