1

Let's say I have the following:

jq 'map(select(. >= 5))'

given [1,2,3,4,5,6,7] it returns:

[5,6,7]

I also have

jq 'map(select(. < 5))'

which given the same data, returns [1,2,3,4]. How can I do these complementary queries at the same time, so that I receive for example:

[1,2,3,4], [5,6,7]
peak
  • 105,803
  • 17
  • 152
  • 177
Maths noob
  • 1,684
  • 20
  • 42

2 Answers2

3

jq has a built-in filter for grouping by some (possibly multi-valued) criterion:

jq -nc '[1,2,3,4,5,6,7] | group_by(. < 5)'

produces:

[[5,6,7],[1,2,3,4]]
peak
  • 105,803
  • 17
  • 152
  • 177
  • oh it has support for groupBy out of the box! lovely :) How do I get the length of each of these partitions? I tried `| map(.length)` but it didn't work ie I want to get [3,4] – Maths noob May 17 '19 at 02:59
  • 1
    You could use `map(length)` to get the lengths of the groups (notice, no dot). – peak May 17 '19 at 03:05
  • thanks a lot! i'm still struggling with manipulation of nested lists. I have asked this separate question which are the minimal versions of the problems i am trying to solve. https://stackoverflow.com/questions/56179292/jq-groupby-and-nested-json-arrays – Maths noob May 17 '19 at 03:48
2

One option is to use reduce:

reduce .[] as $x
([]; if $x < 5 then .[0] += [$x] else .[1] += [$x] end)

This will produce:

[[1,2,3,4],[5,6,7]]
oguz ismail
  • 1
  • 16
  • 47
  • 69