我正在研究一个在大文件中有很多json文档的项目,我们可以将其称为manifest.json
A-11.json
{"id":"a-11","name":"XN0","code":"H3A8FF82820F"
"status":"live"
}
A-03.json
{"id":"a-03","name":"PF1","code":"FFFF82820F"
"status":"live"
}
A-09.json
{"id":"a-09","code":"FFFF82820F"
"status":"live"
}
我想要一个shell脚本做的是以alpha顺序连接它们,我还需要像这样包装它们:
[
{json doc},
{json doc},
{json doc
]
用一个sq括号分隔a,使它看起来像下面的代码 –
join命令只连接两个文件,这样就无法工作了,我尝试了cat和ls的组合,但这一切都有点不对劲.我试图在这里使用Linux环境而不是MS环境.
的manifest.json
[
{"id":"a-03","code":"FFFF82820F"
"status":"live"
},{"id":"a-09",{"id":"a-11","code":"H3A8FF82820F"
"status":"live"
}
]
命令
cat a-*.json > manifest.json
给我以下a-11.json doc在顶部,任何帮助赞赏.
[
{"id":"a-11","code":"H3A8FF82820F"
"status":"live"
}
{"id":"a-03",]
最佳答案
使用以下bash脚本(它使用不是所有shell的标准数组):
原文链接:https://www.f2er.com/linux/440783.html#!/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