[英]Parse 2 files based on key value and recreate another json file [JQ]
[英]I am trying to retrieve the value of a key based on another key of a json in bash scripting without the use of jq
我有一个json文件,需要根据同一个json中“Id”字段的值从json 中检索名称。 我需要用 bash 脚本来做到这一点。 我可以使用sed
、 awk
、 grep
但不能使用jq
。
[
{
"attributes":{
"type":"chocolate","url":"/services/chocolate"
},
"Id":"1",
"Name":"Chocolaty chocloate"
},
{
"attributes":{
"type":"Fruit","url":"/services/fruit"
},
"Id":"2",
"Name":"Fruity Apple"
},
{
"attributes":{
"type":"drink","url":"/services/drink"
},
"Id":"3",
"Name":"Milk Shake"
},
{
"attributes":{
"type":"food","url":"/services/food"
},
"Id":"4",
"Name":"Noodles"
}
]
在上面的例子中,如果我将值“3”传递给脚本,我希望“Id”的名称值为“3” ,即Milk Shake
。
最好的解决方案是使用 jq。 但如果它应该是 sed,你可以在这里做:
#!/bin/bash
sed -n "/\"Id\":\"$2\"/,/\"Name\"/s/.*\"Name\":\"\([^\"]*\).*/\1/p" "$1"
用法
script.sh file.json 3
输出
Milk Shake
假设这两行总是彼此相邻, GNU grep
管道(在函数中)可以工作:
foo() { grep -A 1 '"Id":"'"$2"'",$' "$1" | grep -o '"[^"]*"$'; }
foo file.json 3
输出:
"Milk Shake"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.