Search code examples
vimvi

Find and replace strings in vim on multiple lines


I can do :%s/<search_string>/<replace_string>/g for replacing a string across a file, or :s/<search_string>/<replace_string>/ to replace in current line.

How can I select and replace words from selective lines in vim?

Example: replace text from lines 6-10, 14-18 but not from 11-13.


Solution

  • The :&& command repeats the last substitution with the same flags. You can supply the additional range(s) to it (and concatenate as many as you like):

    :6,10s/<search_string>/<replace_string>/g | 14,18&&
    

    If you have many ranges though, I'd rather use a loop:

    :for range in split('6,10 14,18')| exe range 's/<search_string>/<replace_string>/g' | endfor