Interactive search/replace regex in Vim?

前端 未结 7 2027
夕颜
夕颜 2020-12-12 10:05

I know the regex for doing a global replace,

     %s/old/new/g

How do you go about doing an interactive search-replace in Vim?

相关标签:
7条回答
  • 2020-12-12 10:07

    Add the flag c (in the vim command prompt):

    :%s/old/new/gc
    

    will give you a yes/no prompt at each occurrence of 'old'.

    "old" is highlighted in the text; at the bottom of the window it says "replace with new (y/n/a/q/l/^E/^y)?)"

    Vim's built-in help offers useful info on the options available once substitution with confirmation has been selected. Use:

    :h :s
    

    Then scroll to section on confirm options. Screenshot below:

    Text that says "[C] Confirm each substitution. [...] CTRL-Y to scroll the screen down"

    For instance, to substitute this and all remaining matches, use a.

    0 讨论(0)
  • 2020-12-12 10:08

    If your replacement text needs to change for each matched occurrence (i.e. not simply choosing Yes/No to apply a singular replacement) you can use a Vim plugin I made called interactive-replace.

    0 讨论(0)
  • 2020-12-12 10:17

    Neovim now has a feature to preview the substitution:

    Image taken from: https://medium.com/@eric.burel/stop-using-open-source-5cb19baca44d Documentation of the feature: https://neovim.io/doc/user/options.html#'inccommand'

    0 讨论(0)
  • 2020-12-12 10:19

    I think you're looking for c, eg s/abc/123/gc, this will cause VIM to confirm the replacements. See :help :substitute for more information.

    0 讨论(0)
  • 2020-12-12 10:21

    I usually use the find/substitute/next/repeat command :-)

    /old<CR>3snew<ESC>n.n.n.n.n.n.n.
    

    That's find "old", substitute 3 characters for "new", find next, repeat substitute, and so on.

    It's a pain for massive substitutions but it lets you selectively ignore some occurrences of old (by just pressing n again to find the next one instead of . to repeat a substitution).

    0 讨论(0)
  • 2020-12-12 10:22

    If you just want to count the number of occurrences of 'abc' then you can do %s/abc//gn. This doesn't replace anything but just reports the number of occurrences of 'abc'.

    0 讨论(0)
提交回复
热议问题