bash - 需要使用 sed 更改 json 文件的值

标签 bash sed

我需要使用 sed 更改 JSON 文件的值,

我看到很多人建议使用 jq、python 或 Perl。

但我在容器内工作,我希望它尽可能简单,所以只有 sed 是我需要的解决方案。

JSON 文件是:

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

我想更改其中的 4 个值:

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

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

“spark.cores.max”:“1”

“期间”:“15”,

所以输出将是:

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

最佳答案

对于 sed 使用以下内容

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

关于bash - 需要使用 sed 更改 json 文件的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45192835/

相关文章:

bash循环遍历子目录中的所有查找

macos - 如果我执行与特定模式匹配的命令,如何让 Bash 提示我?

regex - 如何使用 sed、grep 或 awk 只获取 token ?

linux - SED 未终止 `s' 命令仅在少数服务器上失败

linux - `set -o errtrace` 在 shell 脚本中做什么?

linux - Bash 脚本 while 循环的意外结果

alias - 如何在 bash 别名中包含参数?

bash - 用 sed 递归替换文本

bash - 在 sed 命令中转义正斜杠

bash - 使用 Shell 工具(sed | awk...等)从给定的 sample.dat 文件计算最大、最小和平均字段值