When using sort_by it is possible to reverse the sort order of a numeric column like this:
$ jq -c -n '[{"a":0,"b":2},{"a":1,"b":2},{"a":1,"b":0},{"a":0,"b":1},{"a":2,"b":0},{"a":2,"b":1},{"a":2,"b":2},{"a":0,"b":0},{"a":1,"b":1}] | sort_by(.b, -.a) | .[]'
{"a":2,"b":0}
{"a":1,"b":0}
{"a":0,"b":0}
{"a":2,"b":1}
{"a":1,"b":1}
{"a":0,"b":1}
{"a":2,"b":2}
{"a":1,"b":2}
{"a":0,"b":2}
Is it somehow possible to reverse the sort order of a string column?
The following example does of course not work:
$ jq -c -n '[{"a":"x","b":2},{"a":"y","b":2},{"a":"y","b":0},{"a":"x","b":1},{"a":"z","b":0},{"a":"z","b":1},{"a":"z","b":2},{"a":"x","b":0},{"a":"y","b":1}] | sort_by(.b, -.a) | .[]'
jq: error (at <unknown>): string ("x") cannot be negated
One solution:
sort_by(.a)
| reverse
| sort_by(.b)
| .[]
In future, please ask usage questions at https://stackoverflow.com/questions/tagged/jq
Just sort the string naturally and then reverse
. | sort_by(.b, .a) | reverse | .[]
UPD yeah, should be done in two steps since the .b should be forward sorted.
@pkoppstein I thought there was some kind of ord/1 function converting character to a code point. Could be a useful thing, wdyt?
@leonid-s-usov - Are you thinking of explode? Note also that a preliminary .| is never necessary.
Right! I was sure there was this conversion but didn't realize it was part of the explode functionality
In that case I have another option (probably there is a better way to write it but the concept should be clear)
sort_by(.b, -(.a | explode | .[0]) ) | .[]
@pkoppstein
Nice solution, thanks!
Sorry to spam the bug tracker, didn't think of stackoverflow.
@leonid-s-usov
Interesting concept. Very suprising that explode does that! Your way only looks at the first character. The solution to sort all characters this way would be sort_by(.b, (.a | explode | map(-.))) | .[]:
$ jq -c -n '[{"a":"tx","b":2},{"a":"ty","b":2},{"a":"ty","b":0},{"a":"tx","b":1},{"a":"tz","b":0},{"a":"tz","b":1},{"a":"tz","b":2},{"a":"tx","b":0},{"a":"ty","b":1}] | sort_by(.b, (.a | explode | map(-.))) | .[]'
{"a":"tz","b":0}
{"a":"ty","b":0}
{"a":"tx","b":0}
{"a":"tz","b":1}
{"a":"ty","b":1}
{"a":"tx","b":1}
{"a":"tz","b":2}
{"a":"ty","b":2}
{"a":"tx","b":2}
Most helpful comment
One solution:
In future, please ask usage questions at https://stackoverflow.com/questions/tagged/jq