pfnuesel
pfnuesel

Reputation: 15350

Search and replace on specific lines in Vim

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

Upvotes: 154

Views: 118125

Answers (5)

romainl
romainl

Reputation: 196866

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.

Upvotes: 80

Dean
Dean

Reputation: 9128

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

:5,12s/foo/bar/gc

Upvotes: 28

suspectus
suspectus

Reputation: 17288

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.

Upvotes: 2

Ingo Karkat
Ingo Karkat

Reputation: 172758

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

Upvotes: 114

eckes
eckes

Reputation: 67177

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/

Upvotes: 12

Related Questions