Search code examples
bashsed

need to change values of json file using sed


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"
      }
    }

Solution

  • For sed use the following

    sed -i '/spark.driver.memory/c\   \"spark.driver.memory\" : \"1gb\",' file.txt
    sed -i '/spark.executor.memory/c\   \"spark.executor.memory\" : \"1gb\",' file.txt
    sed -i '/spark.cores.max/c\   \"spark.cores.max\" : \"1\",' file.txt
    sed -i '/period/c\   \"period\" : \"15\",' file.txt