0

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.

sush
  • 95
  • 2
  • 8
  • you were given two different suggestions for this in previous question you asked(https://stackoverflow.com/questions/49813321/find-and-replace-text-in-json-with-sed) ... did you try them? – Sundeep Apr 16 '18 at 09:08
  • Yes, I tried all the given options but no luck. sed -i 's/("checksum": ")[^"]*(")/\1 "'"$checksumVal"'"'\2/g' new.json This command is also not working as expected. – sush Apr 16 '18 at 09:23

2 Answers2

1

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
Abhijit Pritam Dutta
  • 5,521
  • 2
  • 11
  • 17
  • Yes, I am getting the output after doing >echo $checksumVal sed -i 's/("checksum": ")[^"]*(")/\1"$checksumVal"\2/g' new.json Error: sed: -e expression #1, char 46: invalid reference \2 on `s' command's RHS First 3 options are not working for me. There are removing the linw which containes checksum word nothing else. – sush Apr 16 '18 at 09:59
  • @sush, I have modified my answer. Try with this and let me know. – Abhijit Pritam Dutta Apr 16 '18 at 11:02
0

What's wrong with jq?:

$ cat foo.json # added the required {}
{"checksum": "sdkjjfj-shbdjfj23"}
$ echo $checksum
foo
$ jq '.checksum = "'"$checksum"'"' foo.json
{
  "checksum": "foo"
}
James Brown
  • 36,089
  • 7
  • 43
  • 59
  • Yes, It is working fine if I create the new json file which contains only checksum field. But my original new.json file containes multiple json fields, there this commad is not working. It is giving following error: parse error: Invalid numeric literal at line 3, column 15. At line 3 there are { characters. – sush Apr 16 '18 at 10:19
  • parse error: Invalid numeric literal at line 3, column 15 Is this error is relevant with jq? – sush Apr 16 '18 at 10:34
  • 1
    Yes, it is always a problem when the question posters do not provide adequate sample data. The solutions are therefore left untested against realistic data. – James Brown Apr 16 '18 at 13:57