0
{
"service " : "namespace",
"name" : "test ",
"name" : "abc",
}

I need to replace the first occurrence of name as "name" : "test 12-12-34 12:09" and the value "12-12-34 12:09" is in some another variable that we can access using $date

Shahaji
  • 175
  • 1
  • 4
  • 14
  • 1
    you should try using `sed` – gogaz Aug 24 '18 at 12:35
  • .. and show what you tried – cdarke Aug 24 '18 at 12:54
  • sed "0,/^.*\"name\"\(.*\)\,$/{s/\(^.*\"name\".*\)\"\,$/\1raw\"\,/}" test.json > abc.json this commad is working fine on linux but not working for Mac – Shahaji Aug 24 '18 at 13:12
  • @gogaz this works on linux but not on mac – Shahaji Aug 24 '18 at 13:14
  • @Shahaji That's not JSON. Why is the file called `test.json`? – chepner Aug 24 '18 at 13:15
  • https://stackoverflow.com/questions/148451/how-to-use-sed-to-replace-only-the-first-occurrence-in-a-file – Benjamin W. Aug 24 '18 at 13:40
  • @chepner this is the JSON file and I am trying to replace the value of key "name" as I shown to above example – Shahaji Aug 24 '18 at 14:45
  • You're missing the commas between the key/value pairs, and while not strictly forbidden, why do you have duplicate `name` keys? In general, you can't assume any particular order for the keys in an object. How do you know the "first" name is the one that needs to change? – chepner Aug 24 '18 at 15:01
  • you should also use a real json parser (such as jq). sed is not a tool meant to parse json. – DTSCode Aug 24 '18 at 17:22
  • @chepner sorry I missed commas when posting this example, I have this document in my NoSQL DB and that is in this format which having multiple "name" keys I need to replace the first occurrence of the key named "name" value to new one. So I am trying to do this and I did that using sed command on Linux but I am not able to run the same command for mac terminal as it does not support some values for sed command. – Shahaji Aug 25 '18 at 16:25
  • @DTSCode I can use JSON parser such as jq as suggested by you but I think this is not a default command which comes with both Linux and mac terminal. I think we need to install it using some specific command for specific OS specific terminal. – Shahaji Aug 25 '18 at 16:28
  • It can also be bundled with your program. Sed is not a JSON parser, and you shouldn't expect it to act like one. If you used proper tools, it would probably work fine on both operating systems – DTSCode Aug 25 '18 at 17:28

0 Answers0