Search and replace in VIM only on specific places

Viewed 35

I have a .json file and I want to search and replace } with },. However, I want to apply this only in the case where I have the text "item_secret": "98ax3fsrv"}. The string 98ax3fsrv will differ both in length and content. So I am actually looking for something like "item_secret": "%s"} and replace it with "item_secret": "%s"},.

Is there any way to apply this search and replace after which combination of strings?

1 Answers

Two different ways come to mind:

1.

:%s/"item_secret": ".*"}/&,

Just a straightforward search and replace. In this, the & represents the entire string that "item_secret": ".*" matched. If there might be more quotes on the line after "98ax3fsrv", you might need either

:%s/"item_secret": "[^"]*"}/&,

or

:%s/"item_secret": ".\{-}"}/&,

2.

:g/item_secret/norm A,

I like this way more. It says "on every line matching item_secret, run the command normal A,", which enters insert mode at the end of the line and appends a comma. This will only work if } is the end of the line everywhere item_secret appears.

Related