我有一個 JSON 檔案,其中包含這樣的串列;
[{
"host": "cat",
"ip": "192.168.1.1",
"id": "cherry"
}, {
"host": "dog",
"ip": "192.168.1.1",
"id": "apple"
}, {
"host": "cat",
"ip": "192.168.1.2",
"id": "banana"
}]
我想收集 IP 并列印id和host旁邊,但如果IP多次使用,則列印多個id和host旁邊而不是新行。IP并且host對于多個專案可以是相同的,但是id是唯一的。
所以最終的輸出應該是這樣的;
$ echo <something>
192.168.1.1 cat cherry dog apple
192.168.1.2 cat banana
如何使用 bash 和 jq 執行此操作?
uj5u.com熱心網友回復:
確保您有一個有效的 JSON 檔案:洗掉,每個物件中的最后一個逗號以將其作為您的input.json:
[{
"host": "cat",
"ip": "192.168.1.1",
"id": "cherry"
}, {
"host": "dog",
"ip": "192.168.1.1",
"id": "apple"
}, {
"host": "cat",
"ip": "192.168.1.2",
"id": "banana"
}]
然后,您只需要一個jq電話:
jq --raw-output 'group_by(.ip)[] | [first.ip, (.[] | .host, .id)] | join(" ")' input.json
演示
uj5u.com熱心網友回復:
修復示例使其成為有效的 JSON 后,該group_by函式是關鍵:
$ jq -r 'group_by(.ip)[] | [.[0].ip, map(.host, .id)[]] | @tsv' input.json
192.168.1.1 cat cherry dog apple
192.168.1.2 cat banana
這會將具有相同 ip 欄位的所有物件組合成一個物件陣列。剩下的就是將這些物件陣列轉換為只包含您想要的值的陣列,最后將每個新陣列輸出為一行制表符分隔值。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/333588.html
