Here are some "pure" awk
solutions:
If the indexes are always the same incrementing integer sequence (6115-6119), as in your sample-data, you can use an algorithmic "shortcut":
awk '{a[$1]=$0} !(NR%4){for(i=6115;i<6119;print a[i++]);}'
This does
- Add all lines to the array
a
, distributed at index positions 6115-6119
- On every 4th line (
!(NR%4)
) , loop through the array contents to print in the desired order.
If your numeric indexes are always the four same ones, but not an incrementing integer sequence, you'll have to sort:
awk '{a[$1]=$0} !(NR%4){asort(a,b); for(i=1;i<5;print b[i++]);}'
Note: This is with GNU awk, others may not support asort
.
If every block-of-four could have different numeric IDs:
awk '{a[$1]=$0} !(NR%4){asort(a); for(i=1;i<5;print a[i++]); delete a}'
Note: TIL from @Gilles self-answer(+2) this use of delete
is not (yet) POSIX, but universally supported.
A version with the correctâ„¢ use of delete
:
awk '{a[$1]=$0} !(NR%4){asort(a); for(i=1;i<5;delete a[i++]){print a[i]}}'
A version without delete, using more memory and dimensions:
awk '{a[n][$1]=$0} !(NR%4){asort(a[n]); for(i=1;i<5;print a[n][i++]); n++}