![](/img/trans.png)
[英]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.