Search and replace in vim in specific lines

Interesting question. Seems like there's only range selection and no multiple line selection:

http://vim.wikia.com/wiki/Ranges

However, if you have something special on line 5 and 12, you could use the :g operator. If your file looks like this (numbers only for reference):

 1     line one
 2     line one
 3     line one
 4     line one
 5     enil one
 6     line one
 7     line one
 8     line one
 9     line one
10     line one
11     line one
12     enil one

And you want to replace one by eno on the lines where there's enil instead of line:

:g/enil/s/one/eno/

Vim has special regular expression atoms that match in certain lines, columns, etc.; you can use them (possibly in addition to the range) to limit the matches:

:5,12s/\(\%5l\|\%12l\)foo/bar/g

See :help /\%l


You could always add a c to the end. This will ask for confirmation for each and every match.

:5,12s/foo/bar/gc

You can do the substitution on line 5 and repeat it with minimal effort on line 12:

:5s/foo/bar
:12&

As pointed out by Ingo, :& forgets your flags. Since you are using /g, the correct command would be :&&:

:5s/foo/bar/g
:12&&

See :help :& and friends.

Tags:

Vim