我需要使用 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"
}
}
Run Code Online (Sandbox Code Playgroud)
我想更改其中的 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"
}
}
Run Code Online (Sandbox Code Playgroud)
对于 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
Run Code Online (Sandbox Code Playgroud)
届时您将准备好使用jq
工具找到正确的解决方案:
jq '.conf |= . + {"spark.driver.memory":"1gb","spark.executor.memory":"1gb","spark.cores.max":"1"} | .schedule |= . + {period:"15"}' file
Run Code Online (Sandbox Code Playgroud)
输出:
{
"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"
}
}
Run Code Online (Sandbox Code Playgroud)