Search and replace in vim in specific lines

Vim

Vim Problem Overview


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)?

Vim Solutions


Solution 1 - Vim

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

Solution 2 - Vim

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.

Solution 3 - Vim

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

:5,12s/foo/bar/gc

Solution 4 - Vim

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/

Solution 5 - Vim

You could use ed - a line oriented text editor with similar commands to vi and vim. It probably predates vi and vim.

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionpfnueselView Question on Stackoverflow
Solution 1 - VimIngo KarkatView Answer on Stackoverflow
Solution 2 - VimromainlView Answer on Stackoverflow
Solution 3 - VimDeanView Answer on Stackoverflow
Solution 4 - VimeckesView Answer on Stackoverflow
Solution 5 - VimsuspectusView Answer on Stackoverflow