![从纯文本输入将数组条目添加到现有 JSON 文档](https://linux22.com/image/131183/%E4%BB%8E%E7%BA%AF%E6%96%87%E6%9C%AC%E8%BE%93%E5%85%A5%E5%B0%86%E6%95%B0%E7%BB%84%E6%9D%A1%E7%9B%AE%E6%B7%BB%E5%8A%A0%E5%88%B0%E7%8E%B0%E6%9C%89%20JSON%20%E6%96%87%E6%A1%A3.png)
我遇到一种情况,我有一个命令的输出,如下所示,
192.168.1.84
192.168.1.85
我想使用这个,并在另一个文件中进行更改,即像这样的形式一个接一个地添加这个IP地址。以下资源记录集线。
ubuntu@kops:/mujahid$ cat change-resource-record-sets.json
{
"Comment": "Update record to reflect new IP address of home router",
"Changes": [
{
"Action": "UPSERT",
"ResourceRecordSet": {
"Name": "testing.mak.online.",
"Type": "A",
"TTL": 60,
"ResourceRecords": [
{
"Value": "192.168.1.84"
},
{
"Value": "192.168.1.5"
}
]
}
}
]
}
答案1
要从 生成的 IP 地址列表创建正确的 JSON somecommand
,请使用jq
:
somecommand | jq -Rs '{
Comment: "Update record to reflect new IP address of home router",
Changes: [ {
Action: "UPSERT",
ResourceRecordSet: {
Name: "testing.mak.online.",
Type: "A",
TTL: 60,
ResourceRecords: split("\n")|.[0:-1]|map({Value:.})
} } ] }'
这导致
{
"Comment": "Update record to reflect new IP address of home router",
"Changes": [
{
"Action": "UPSERT",
"ResourceRecordSet": {
"Name": "testing.mak.online.",
"Type": "A",
"TTL": 60,
"ResourceRecords": [
{
"Value": "192.168.1.84"
},
{
"Value": "192.168.1.85"
}
]
}
}
]
}
鉴于somecommand
输出
192.168.1.84
192.168.1.85
答案2
您可以将输入存储在数组中,并通过循环输出所有内容。
#!/bin/bash
OLDIFS=$IFS
IFS=' '
ARR=($@)
for i in "${ARR[@]}"
do
echo $i >>/output/file.txt
done
IFS=$OLDIFS
该脚本将逐行输出您输入的所有内容。
示例调用:thisscript.sh $(command that generates your IP's)