Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Use jq to remove the last three elements of an array

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading