Search and replace in Vim across all the project files

后端 未结 11 1908
我寻月下人不归
我寻月下人不归 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条回答
  •  不知归路
    2020-12-07 07:46

    maybe do this:

    :noautocmd vim /Search/ **/*
    :set hidden
    :cfirst
    qa
    :%s//Replace/gce
    :cnf
    q
    1000@a
    :wa
    

    Explanation:

    • :noautocmd vim /Search/ **/* ⇒ lookup (vim is an abbreviation for vimgrep) pattern in all files in all subdirectories of the cwd without triggering autocmds (:noautocmd), for speed's sake.
    • :set hidden ⇒ allow having modified buffers not displayed in a window (could be in your vimrc)
    • :cfirst ⇒ jump to first search result
    • qa ⇒ start recording a macro into register a
    • :%s//Replace/gce ⇒ replace all occurrences of the last search pattern (still /Search/ at that time) with Replace:
      • several times on a same line (g flag)
      • with user confirmation (c flag)
      • without error if no pattern found (e flag)
    • :cnf ⇒ jump to next file in the list created by the vim command
    • q ⇒ stop recording macro
    • 1000@a ⇒ play macro stored in register a 1000 times
    • :wa ⇒ save all modified buffers

    * EDIT * Vim 8 way:

    Starting with Vim 8 there is a better way to do it, as :cfdo iterates on all files in the quickfix list:

    :noautocmd vim /Search/ **/*
    :set hidden
    :cfdo %s//Replace/gce
    :wa
    

提交回复
热议问题