Reputation: 25
If I want the closest numbers to 7 out of a range of 1-10, the expected outcome I would like is:
7, 6, 8, 5, 9, 4, 10, 3, 2, 1
I've looked around and can't really find an answer, is it even doable?
Pretty much trying to take an array with a series of numbers, and sorting them based on a target number with the closest at the top, and furthest towards the bottom.
Upvotes: 0
Views: 215
Reputation: 140970
Print the numbers on newlines
Compute the absolute value of the difference between target number and a number on each line
Sort using that computed value
Remove that computed value
Format output
seq 10 |
awk -vN=7 '{print abs($1-N),$1} function abs(x) { return x < 0 ? -x : x; }' |
sort -n |
cut -d' ' -f2 |
paste -sd,
Upvotes: 2