json - 如何使用bash替换json中的文本
问题描述
我正在尝试使用 JSON 文件中的 bash 将qa_test_services替换为test_services,有人可以帮我解决这个问题吗?谢谢
JSON 文件 - variables.json
{
"variable": {
"qa_test_services": {
"default": {
"prod-test-1": {
"position": 0,
"service_name": "test-1-service"
},
"prod-test-2": {
"position": 1,
"service_name": "test-2-service"
}
}
}
}
}
bash - 脚本
test_json="variables.json"
actual_text="qa_test_services"
replace_text="test_services"
SEARCH_LINE=`cat $test_json | grep $actual_text | sed 's/"//g' | sed 's/://g' | sed 's/{//g' | sed -e 's/ */ /g'`
echo $SEARCH_LINE
解决方案
我会避免使用面向行的工具编辑 json 的诱惑。像 xml 一样,它的格式并不总是很好。尝试使用 jq; 这就像 sed 的 json。
jq -f filter.jq variables.json
过滤器.jq
.variable |= with_entries(
if .key == "qa_test_services" then
.key = "test_services"
else
.
end)
输出
{
"variable": {
"test_services": {
"default": {
"prod-test-1": {
"position": 0,
"service_name": "test-1-service"
},
"prod-test-2": {
"position": 1,
"service_name": "test-2-service"
}
}
}
}
}
使用 bash 变量
jq ".variable |= with_entries(
if .key == \"$actual_text\" then
.key = \"$replace_text\"
else
.
end)" $test_json
推荐阅读
- sql - BigQuery 疑难解答 - 查询还是 Google Analytics?
- .htaccess - 阻止指向我的网站的不需要的域名
- php - PHP中的“i360:全局初始化错误”是什么意思?
- r - Removing rows where multiple columns equal an exact number R
- python - 安排脚本每天运行并存储数据 AWS
- python-3.x - 无法使用 boto2 将资格分配给 Mechanical Turkers
- asp.net-web-api2 - 在单个控制台应用程序中自托管 SignalR 和 Web Api
- google-cloud-datalab - Datalab 提供 1.2.20180713 的可选升级,这在 GitHub 版本中不存在
- r - 关于点和多边形的叶绿素的次要图例,ggplot
- sql-server - 对于存储过程,我可以更改 SSMS UI 中“执行”命令的默认行为吗?