あんパン

こしあん派

jqで複数ファイルに分割されたJSONの配列の要素数を合計する

jq -s 'add | length' ./*.json でいける。

$ cat a.json
[1, 2, 3, 4]
$ cat b.json
[5, 6, 7, 8, 9]
$ jq -s 'add | length' ./*.json
9

-s--slurp の略らしい。

-s, --slurp read all inputs into an array

以下のように挙動を追うとよく分かる。

$ jq '.' ./*.json
[
  1,
  2,
  3,
  4
]
[
  5,
  6,
  7,
  8,
  9
]
$ jq -s '.' ./*.json
[
  [
    1,
    2,
    3,
    4
  ],
  [
    5,
    6,
    7,
    8,
    9
  ]
]
$ jq -s '. | add' ./*.json
[
  1,
  2,
  3,
  4,
  5,
  6,
  7,
  8,
  9
]
$ jq -s '. | add | length' ./*.json
9