将多行转换为以逗号分隔的单行

问题描述 投票:0回答:1

有一个包含大量记录的 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。

design-patterns matching
1个回答
0
投票
$ 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"
© www.soinside.com 2019 - 2024. All rights reserved.