I can use
:5,12s/foo/bar/g
to search for foo and replace it by bar between lines 5 and 12. How can I do that only in line 5 and 12 (and not in the lines in between)?
foo
bar
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):
:g
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:
one
eno
enil
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
:help /\%l
You could use ed - a line oriented text editor with similar commands to vi and vim. It probably predates vi and vim.
ed
In a script (using a here document which processes input till the EndCommand marker) it would look like:
ed file <<EndCommands 5 s/foo/bar/g 7 s/foo/bar/g wq EndCommands
Obviously, the ed commands can be used on the command line also.
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 :&&:
:&
/g
:&&
:5s/foo/bar/g :12&&
See :help :& and friends.
:help :&
You could always add a c to the end. This will ask for confirmation for each and every match.
c
:5,12s/foo/bar/gc