getshrekt
getshrekt

Reputation: 219

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

For instance, if I had:

eat eat eat eat cake cake

eat eat eat cake

cake eat eat cake

How would I replace 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

Upvotes: 21

Views: 22126

Answers (1)

Prasanna
Prasanna

Reputation: 1274

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

Upvotes: 35

Related Questions