sush
sush

Reputation: 95

Find and replace text in JSON with sed using shell variables

Actually my JSON looks like below:

"checksum": "sdkjjfj-shbdjfj23"

I wanted to replace the checksum value with another value. As per above I used :

sed -i 's/("checksum": ")[^"]*(")/\1$checksumVal\2/g' new.json

The new.json is updated as below, but i wanted the value of that variable.

"checksum": "$checksumVal",

Expected Result:

"checksum": "newval"

Any help would be appreciated.

Upvotes: 0

Views: 1501

Answers (2)

Abhijit Pritam Dutta
Abhijit Pritam Dutta

Reputation: 5591

First of all use one echo statement and check whether $checksumVal has some value or not and also try like below it work for me. How will it work sed "/checksum will search for pattern "checksum once it found the pattern it will search for pattern : "*" (with wild card) in this example it is : "sdkjjfj-shbdjfj23" and this pattern will be replace with : "$checksumVal"

 sed "/checksum/s/: ".*"/: \"$checksumVal\"/" new.json

Upvotes: 1

James Brown
James Brown

Reputation: 37404

What's wrong with jq?:

$ cat foo.json # added the required {}
{"checksum": "sdkjjfj-shbdjfj23"}
$ echo $checksum
foo
$ jq '.checksum = "'"$checksum"'"' foo.json
{
  "checksum": "foo"
}

Upvotes: 0

Related Questions