Darzen
Darzen

Reputation: 1135

vim : Find a pattern, skip a word and append something in all matching lines

I am aware of the simple search and replace commands (:%s/apple/orange/g) in vim where we find all 'apples' and replace them with 'orange'.

But is it possible to do something like this in vim? Find all 'Wheat' in a file and append "store" after skipping the next word (if any)?

Example: Original file contents :

Wheat flour
Wheat bread
Rice flour
Wheat

After search and replace:

Wheat flour store
Wheat bread store
Rice flour
Wheat store

Upvotes: 0

Views: 356

Answers (1)

DJMcMayhem
DJMcMayhem

Reputation: 7669

This is the perfect time to use the global command. It will apply a command to every line that matches a given regex.

                        *:g* *:global* *E147* *E148*
:[range]g[lobal]/{pattern}/[cmd]
            Execute the Ex command [cmd] (default ":p") on the
            lines within [range] where {pattern} matches.

In this case, the command is norm A store and the regex is wheat. So putting it all together, we have

:g/Wheat/norm A store

Now, you could do this with the substitute command, but I find global is a lot more convenient and readable. In this case, you'd have:

:%s/Wheat.*/& store

Which means:

:%s/                " On every line, replace...
    Wheat           "   Wheat
         .*         "   Followed by anything
           /        " with...
            &       "   The entire line we matched
              store "   Followed by 'store'

Upvotes: 5

Related Questions