curious_brain
curious_brain

Reputation: 403

Replace the string in a file in Unix - replace the part of the matching regular expression

I have a JSON document with such a repeating structure

{"version":"21.0.0.1","artifact":"artifact","payload":[{"id":"ng-at-ng/at","name":"ng/at","location":"apmservices/at:21.3.0.2-linux-amd64","component":"core","tag":"21.3.0.2-linux-amd64"},{"id":"doi-dspintegrator-doi/dspintegrator","name":"doi/dspintegrator","location":"doi/1.3.    3/dspintegrator:2.0.0-RELEASE_183","component":"doi","tag":"2.0.0-RELEASE_183"}]}

I want to replace the value of all "location" tags with - wherever there is a /. So after the replacement, the above text becomes:

{"version":"21.0.0.1","artifact":"artifact","payload":[{"id":"ng-at-ng/at","name":"ng/at","location":"apmservices-at:21.3.0.2-linux-amd64","component":"core","tag":"21.3.0.2-linux-amd64"}, {"id":"doi-dspintegrator-doi/dspintegrator","name":"doi/dspintegrator","location":"doi-1.3.3-dspintegrator:2.0.0-RELEASE_183","component":"doi","tag":"2.0.0-RELEASE_183"}]}

Note that there can be multiple / and - in the value of "location" tags in the original JSON document.

Reading through some other posts, it appears that -E option in sed with capture should be used but I am not sure how to make it work. Please can someone help?

Upvotes: 0

Views: 42

Answers (1)

peak
peak

Reputation: 116690

Using :

.payload[].location |= gsub("/";"-")

Or, if you want every "location" key checked, irrespective of where the key occurs:

walk(if type == "object" and (.location|type=="string") 
     then .location |= gsub("/";"-") else . end)

Upvotes: 1

Related Questions