Shell脚本将5个或更多json文件连接在一起

时间:2014-04-30 11:46:47

标签: json linux shell cat

我正在研究一个在大文件中有很多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",
 "name":"PF1",
 "code":"FFFF82820F"
 "status":"live"
} 

我想要一个shell脚本做的是以alpha顺序连接它们,我还需要像这样包装它们:     [     {json doc},     {json doc},     {json doc     ] 用一个sq括号分隔a,使它看起来像下面的代码 -

join命令只连接两个文件,这样就无法工作了,我尝试了cat和ls的组合,但这一切都有点不对劲。我试图在这里使用Linux环境而不是MS环境。

的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 doc在顶部,任何帮助表示赞赏。

[
{"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"
}, 

]

2 个答案:

答案 0 :(得分:19)

您可以使用jq utility (sed for JSON data)

$ jq -s '.' a-*.json > manifest.json

的manifest.json:

[
  {
    "status": "live",
    "code": "H3A8FF82820F",
    "name": "XN0",
    "id": "a-11"
  },
  {
    "status": "live",
    "code": "FFFF82820F",
    "name": "PF1",
    "id": "a-03"
  },
  {
    "status": "live",
    "code": "FFFF82820F",
    "name": "PF1",
    "id": "a-09"
  }
]

答案 1 :(得分:7)

使用以下 bash 脚本(它使用的数据在所有shell中都不是标准的):

#!/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