I’m trying to use jq
to get an array from a json object and I need to remove the last three elements of this array. So this is what I did so far:
echo '{ "tags": [ "2.9.7", "2.9.8", "2.9.9", "2.9.10", "2.9.11", "2.9.12" ]}' | jq -r '.tags | sort[:3][]'
gives me 2.9.10 2.9.11 2.9.12
, but need it the other way round. These values should be removed, so the result should be:
2.9.7 2.9.8 2.9.9
>Solution :
Start the index counter at the third-last element [-3
, and go until the end :]
:
… | jq -r '.tags | sort[-3:][]'
2.9.7
2.9.8
2.9.9
Watch out, however, as you are sorting strings here, where 2.9.12
will be sorted before 2.9.7
. If you want to sort the array by version numbers (structured as seen), split them at the dot into an array, convert the items into numbers, and sort by that:
… | jq -r '.tags | sort_by(split(".") | map(tonumber))[:3][]'
2.9.7
2.9.8
2.9.9