Find and Prepend

VIM actually allows you to find and prepend stuff which is something quite unique compared to majority of the text editors. The idea is to "find and capture" the keywords and then re-insert back in the replace component. The general form is as such:

:%s/^\(keywords\)$/prependWord \1/

Notations

  • %s - range of effect. This is similar to Find and Replace range.
  • ^ - start of line
  • \( - begin capturing
  • keywords - your keywords
  • \) - end capturing
  • $ - end of line
  • \1 - fills in the captured keywords by capturing sequence. (e.g. first capture is 1, second capture is 2, ...)

Find and Prepend By Keywords

You can find and prepend keywords by performing the capturing. The pattern is:

:%s/\(keywords\)/prependWord \1/

Notice that we do not need the start of line and end of line indicator.


Example

badFilepath
badInput

Run with:

:%s/\(bad\)/cool\1/

Ends up with:

coolbadFilepath
coolbadInput


Find and Prepend By Line

You can find and prepend line by performing the capturing. The pattern is:

:%s/^\(keywords\)$/prependWord \1/


Example

badFilepath
badInput

Run with:

:%s/^\(badInput\)$/cool Coolie\r\1/

Ends up with:

badFilepath
cool Coolie
badInput

That's all about find and prepend in VIM.