Shell脚本将5个或更多json文件连接在一起 [英] Shell script to join 5 or more json files together
问题描述
我正在一个项目中,该项目在一个大文件中包含很多json文档,可以将其称为manifest.json
I am working on a project that has a lot of json documents in a large file lets call it manifest.json
文件的标题如
a-11.json
a-11.json
{"id":"a-11",
"name":"XN0",
"code":"H3A8FF82820F"
"status":"live"
}
a-03.json
a-03.json
{"id":"a-03",
"name":"PF1",
"code":"FFFF82820F"
"status":"live"
}
a-09.json
a-09.json
{"id":"a-09",
"name":"PF1",
"code":"FFFF82820F"
"status":"live"
}
我想要shell脚本执行的操作是按alpha顺序将它们全部连接起来,我还需要像这样包装它们: [ {json doc}, {json doc}, {json doc ] 用方括号括起来的方括号,使它看起来像下面的代码-
What I want a shell script to do is to concatenate them all in alpha order and I am also need to wrap them like this: [ {json doc}, {json doc}, {json doc ] with a sq bracket seperated with a , so that it looks like the code below-
join命令仅连接两个文件,因此无法正常工作,我尝试了cat和ls的组合,但都出错了.我试图在这里使用Linux环境而不是MS环境.
The join command only connects two files so thats not going to work and I have tried a combination of cat and ls but it all goes a bit wrong. I am trying to use the Linux environment rather than the MS environment here.
manifest.json
manifest.json
[
{"id":"a-03",
"name":"PF1",
"code":"FFFF82820F"
"status":"live"
},
{"id":"a-09",
"name":"PF1",
"code":"FFFF82820F"
"status":"live"
},
{"id":"a-11",
"name":"XN0",
"code":"H3A8FF82820F"
"status":"live"
}
]
命令
cat a-*.json > manifest.json
为我提供以下内容,并在顶部显示a-11.json文档,感谢您的帮助.
Gives me the following with the a-11.json doc at the top, any help appreciated.
[
{"id":"a-11",
"name":"XN0",
"code":"H3A8FF82820F"
"status":"live"
}
{"id":"a-03",
"name":"PF1",
"code":"FFFF82820F"
"status":"live"
},
{"id":"a-09",
"name":"PF1",
"code":"FFFF82820F"
"status":"live"
},
]
推荐答案
使用以下 bash 脚本(它使用并非所有shell都标准的数组):
Use the following bash script (it uses arrays which aren't standard across all shells):
#!/bin/bash
shopt -s nullglob
declare -a jsons
jsons=(a-*.json) # ${jsons[@]} now contains the list of files to concatenate
echo '[' > manifest.json
if [ ${#jsons[@]} -gt 0 ]; then # if the list is not empty
cat "${jsons[0]}" >> manifest.json # concatenate the first file to the manifest...
unset jsons[0] # and remove it from the list
for f in "${jsons[@]}"; do # iterate over the rest
echo "," >>manifest.json
cat "$f" >>manifest.json
done
fi
echo ']' >>manifest.json # complete the manifest
这篇关于Shell脚本将5个或更多json文件连接在一起的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!