Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Vim, how would I replace the only the first occurrence of a certain word in each line with another word?

Tags:

vim

For instance, if I had:

eat eat eat eat cake cake

eat eat eat cake

cake eat eat cake

How would I only the first instance of cake in each line with pear?

eat eat eat eat pear cake

eat eat eat pear

pear eat eat cake

like image 983
getshrekt Avatar asked Nov 25 '15 05:11

getshrekt


1 Answers

Use following

:%s/cake/pear/

Note that if you append 'g' flag to the above expression, the search happens globally over the entire line. The initial '%' character indicates the range over which the replacement should happen. % means whole file (or all lines in the file).

So following does replacement of only first occurrence on each line

:%s/cake/pear/

And following does replacement of all occurrences on each line

:%s/cake/pear/g
like image 77
Prasanna Avatar answered Oct 05 '22 07:10

Prasanna