How to Prepend/Append a Search Match in Vim

The aim of this pagešŸ“ is to provide two alternatives to quickly prepend or append text to a search match in Vim. In my simple case, have a string ā€œTrackingā€ all across a JSON config object and I need to change it into ā€œResponsible Trackingā€, without repeating ā€˜Trackingā€™ in the replace field.

Pavol Kutaj
Sep 13, 2024

As usual, I separate the search and replace it into two steps as it may take several iterations of the search to get it right, mainly if using regex.

global

  • with g command
  • search with /<search_pattern>
  • replace with an Ex commandg##s##<prepend_append_with>&#g

magic

  • with very magick mode
  • search with /\v(<search_pattern>) --> The () defines capturing (aka match) group within search without the need to escape parents
  • replace with an Ex command %s##<prepend_with>\1#g

Links

--

--

Pavol Kutaj

Today I Learnt | Infrastructure Support Engineer at snowplow.io with a passion for cloud infrastructure/terraform/python/docs. More at https://pavol.kutaj.com