TL;DR: Given an input file with a series of keypairs, I want to select the 3rd-to-last and 4th-to-last pairs. I can get them individually, but I want to grab both at once if possible. Can this be done?
My input file is structured like this;
[
{
"foo": "bar",
"foo2": "bar2"
},
{
"foo3": "bar3",
"foo4": "bar4"
},
{
"foo5": "bar5",
"foo6": "bar6"
},
{
"foo7": "bar7",
"foo8": "bar8"
},
{
"foo9": "bar9",
"foo10": "bar10"
}
]
And my output should be
[
{
"foo3": "bar3",
"foo4": "bar4"
},
{
"foo5": "bar5",
"foo6": "bar6"
}
]
I know I can do jq -s '.[-3]'
to get the 3rd-to-last (and swap with a 4 for the 4th-to-last) but that grabs them separately.
I thought from the documentation that jq -s '.[-3;-4]'
would grab both but that throws an error.
I could grab them individually and work on each separately but that's sloppy code. Is there a cleaner way to grab both at once?
If you want to select ranges of values in an array, you could use the slice syntax:
<start-index>:<end-index>
Just remember that the ending index is exclusive (and not inclusive) and should be increasing order.
So to get the third/fourth from the end:
.[-4:-2]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With