Search and replace in vim on specific lines

I can use

:5,12s/foo/bar/g 

to search for foo and replace it with bar between lines 5 and 12. How can this be done only on lines 5 and 12 (and not on the lines between them)?

+56
vim
Jun 26 '13 at 12:06 on
source share
5 answers

Vim has special regex atoms that match specific rows, columns, etc .; you can use them (perhaps in addition to the range) to limit matches:

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

See :help /\%l

+41
Jun 26 '13 at 12:21
source share
— -

You can make a replacement on line 5 and repeat it with minimal effort on line 12:

 :5s/foo/bar :12& 

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

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

See :help :& and friends.

+35
Jun 26 '13 at 13:03
source share

You can always add c to the end. This will require confirmation for each match.

 :5,12s/foo/bar/gc 
+8
Jun 26 '13 at 15:43
source share

Interest Ask. It seems that only range selection and multiple row selection:

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

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

  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 on eno with lines where enil instead of line :

 :g/enil/s/one/eno/ 
+6
Jun 26 '13 at 12:18
source share

You can use ed , a text-based text editor with similar commands for vi and vim. This is probably preceded by vi and vim.

In the script (using the document here, which processes the input before the EndCommand token), it will look like this:

 ed file <<EndCommands 5 s/foo/bar/g 7 s/foo/bar/g wq EndCommands 

Obviously ed commands can also be used on the command line.

+2
Jun 26 '13 at 12:24
source share



All Articles