我有一个文本文件,其中包含以下JSON输出。只要组中包含“ IP”,我希望能够合并数据。我想使用jq或sed / awk。我愿意接受其他bash命令。
{"Front":[
{"Name":"new.domain.com-80", "Out":"8.8.8.8", "In":"192.168.2.2:80", "W Name":"new.domain.com-80", "Groups":"192.168.3.29:80 192.168.3.30:80"},
{"Name":"new.domain.com -443", "Out":"8.8.8.8", "In":"192.168.2.2:443", "W Name":"new.domain.com-443", "Groups":"192.168.3.29:443 192.168.3.30:443"}
]}
{"Back":[
{"REC":"", "IP":"192.168.3.30", "Host":"new2.domain.com", "Info":"Worker5 MD: Data source - Owner: Q"},
{"REC":"Q", "IP":"192.168.3.29", "Host":"new3.domain.com", "Info":"Worker5 MD: Data source - Owner: Q"},
{"REC":"Q"}
]}
如果IP包含在组中,则添加主机和信息。 我们可以忽略REC
预期输出:
{"Front":[
{"Name":"new.domain.com-80", "Out":"8.8.8.8", "In":"192.168.2.2:80", "W Name":"new.domain.com-80", "Groups":"192.168.3.29:80 192.168.3.30:80", "Host":"new2.domain.com,new3.domain.com", "Info":"Worker5 MD: Data source - Owner: Q,Worker5 MD: Data source - Owner: Q"},
{"Name":"new.domain.com-443", "Out":"8.8.8.8", "In":"192.168.2.2:443", "W Name":"new.domain.com-443", "Groups":"192.168.3.29:443 192.168.3.30:443", "Host":"new2.domain.com,new3.domain.com", "Info":"Worker5 MD: Data source - Owner: Q,Worker5 MD: Data source - Owner: Q"}
]}
答案 0 :(得分:2)
以下内容假设Front和Back对象以顺序显示在STDIN或文件中;在这种假设下,应使用-n命令行选项调用以下程序。
input as $front
| input as $back
| ($back|INDEX(.Back[]; .IP) | map_values({Host,Info})) as $dict
| $front
| .Front[]
|= reduce ($dict | keys_unsorted[]) as $k (.;
if (.Groups | contains($k)) then . + $dict[$k] else . end)
我使用reduce
遍历IP值,因为这样做可以提供灵活性,以防您想以某种特定方式处理冲突。
一种可能性:
jq -n -f program.jq input.json