Search & replace using quickfix list in Vim

前端 未结 6 1797

So far I always used EasyGrep for replacing text in multiple files. Unfortunately it is quite slow when a project gets bigger. One thing that seems to be amazingly fast is G

6条回答
  •  眼角桃花
    2020-12-07 11:05

    Update: Vim now has cdo, see Sid's answer.

    Original Answer:

    Vim has bufdo, windo, tabdo and argdo, which let you perform the same command in all open buffers, windows or files in the argument list. What we really need is something like quickfixdo, which would invoke a command on every file in the quickfix list. Sadly, that functionality is lacking from Vim, but here's a solution by Al that provides a home-rolled solution. Using this, it would be possible to run:

    :QFDo %s/foo/bar/gc
    

    And that would run the foo/bar substitution on all files in the quickfix list.

    The bufdo, windo, tabdo and argdo commands have some common behaviour. For example, if the current file can't be abandoned, then all of these commands will fail. I'm not sure if the QFDo command referenced above follows the same conventions.

    I've adapted Al's solution to create a command called Qargs. Running this command populates the argument list with all of the files listed in the quickfix list:

    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
    

    Using this, you could follow these steps to do a project-wide search and replace:

    :Ggrep findme
    :Qargs
    :argdo %s/findme/replacement/gc
    :argdo update
    

    Edit: (with a hat tip to Peter Rincker)

    Or you could join the last 3 commands together in a single line:

    :Ggrep findme
    :Qargs | argdo %s/findme/replacement/gc | update
    

提交回复
热议问题