2

Given

[3,4]
[5,2]

I'd like to produce:

[5,2]
[3,4]

I tried this but it fails:

echo '[3,4] [5,2]' | jq 'sort_by(.[1])'

jq: error (at <stdin>:1): Cannot index number with number
jq: error (at <stdin>:1): Cannot index number with number

1 Answer 1

6

Use -n with inputs to access the stream's items. [‌...] collects them into an outer array, sort_by(...) sorts by criteria, ...[] decomposes the outer array again, and -c makes the output compact

jq -nc '[inputs] | sort_by(.[1])[]'
[5,2]
[3,4]

Demo

Sign up to request clarification or add additional context in comments.

3 Comments

Oh whoops sorry my example was incorrect, I actually want to sort on the second element in the array... I've updated it to make this clearer. Is there a way to adapt your solution to the updated question?
@tekumara Sure, just change sort to sort_by(.[1]). Updated.
You can replace -n + [inputs] with -s aka --slurp: jq -sc 'sort_by(.[1])[]'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.