need to change values of json file using sed

Viewed 15889

I need to change values of JSON file using sed,

I saw a lot of people suggesting using jq, python, or Perl.

But I'm working inside a container and I want it to be as simple as possible so only sed is the needed solution for me.

the JSON file is:

{
  "useCaseName" : "rca",
  "algorithm" : "log-clustering-train",
  "mainClass" : "com.hp.analytics.logclustering.MainTrainer",
  "applicationJar" : "log-clustering-train-1.0.0-SNAPSHOT-jar-with-dependencies.jar",
  "conf" : {
    "spark.driver.memory" : "3gb",
    "spark.executor.memory" : "9gb",
    "spark.executor.userClassPathFirst" : "true",
    "spark.cores.max": "8"
  },
  "schedule" : {
    "period" : "10",
    "timeUnit" : "hours",
    "timeoutPeriodSeconds" : "10800"
  }
}

And I want to change 4 values inside it:

"spark.driver.memory" : "1gb",

"spark.executor.memory" : "1gb",

"spark.cores.max" :"1"

"period" : "15",

So the output will be:

  {
      "useCaseName" : "rca",
      "algorithm" : "log-clustering-train",
      "mainClass" : "com.hp.analytics.logclustering.MainTrainer",
      "applicationJar" : "log-clustering-train-1.0.0-SNAPSHOT-jar-with-dependencies.jar",
      "conf" : {
        "spark.driver.memory" : "1gb",
        "spark.executor.memory" : "1gb",
        "spark.executor.userClassPathFirst" : "true",
        "spark.cores.max": "1"
      },
      "schedule" : {
        "period" : "15",
        "timeUnit" : "hours",
        "timeoutPeriodSeconds" : "10800"
      }
    }
4 Answers

Below will work for both mac and linux.

If you want to read from some variable name value, use first command and if you have direct value, use second command.

sed -ie 's/"key1": .*"/"key1": '\"${value}\"'/g' filename
sed -ie 's/"key1": .*"/"key1": '\"yourvalue\"'/g' filename

Related