Skip to main content
1 of 4
Stéphane Chazelas
  • 585.1k
  • 96
  • 1.1k
  • 1.7k

A shell is before all a tool to run other tool. It sounds to me you're after a programming language like perl, ruby, python...

Having said that, here is some possible solution for zsh.

In zsh, you can get a sorted list of the keys of an associated array (${(kOn)A}) or of the values (${(On)A}) but not directly a list of keys from the sorted list of values (AFAIK), but you could do things like:

typeset -A A B
A=(
  192.168.2.2 5
  192.168.3.2 1
  192.168.1.1 9
  192.168.8.1 9
)

for v ("${(@nO)A}") B+=("${(@kv)A[(eR)$v]}")

Then, you'd get the sorted list in B:

$ printf '%s => %s\n' "${(@kv)B}"
192.168.8.1 => 9
192.168.1.1 => 9
192.168.2.2 => 5
192.168.3.2 => 1

And you can select the first 2 keys with

$ print -rl -- ${${(k)B}[1,2]}
192.168.8.1
192.168.1.1
Stéphane Chazelas
  • 585.1k
  • 96
  • 1.1k
  • 1.7k