有一个包含大量记录的 json 文件,如下所示。我需要提取 4 个字段并将它们放入一行输出中,如下所示
{,
"address": "122.22.33.33",
"ipv6_prefix_bits": "0",
"protocol": "IPV4",
"network": "10.118.121.11/14",
"hostname": "abcd.net",
"state": "active"
.....
},
{,
"address":......
...
...
},
OUTPUT
"hostname": "abcd.net","protocol": "IPV4","network": "10.118.121.11/14","state": "active"
"hostname":.....
,
我尝试了 JQ,但是我需要在没有 JQ 的生产服务器中执行此操作,因此可能必须使用 AWK 或 SED。
$ cat input.json
[
{
"address": "122.22.33.33",
"ipv6_prefix_bits": "0",
"protocol": "IPV4",
"network": "10.118.121.11/14",
"hostname": "abcd.net",
"state": "active"
},
{
"address": "122.22.33.34",
"ipv6_prefix_bits": "0",
"protocol": "IPV4",
"network": "10.118.121.11/14",
"hostname": "efgh.net",
"state": "active"
}
]
$ awk '
{ sub(/^ */,"") }
/^"hostname":/{ hostname=$0 }
/^"protocol":/{ protocol=$0 }
/^"network":/{ network=$0 }
/^"state":/{
sub(/,$/,"")
state=$0
printf "%s %s %s %s\n", hostname, protocol, network, state
}
' input.json
"hostname": "abcd.net", "protocol": "IPV4", "network": "10.118.121.11/14", "state": "active"
"hostname": "efgh.net", "protocol": "IPV4", "network": "10.118.121.11/14", "state": "active"