Bash associative array sorting by value

Graf picture Graf · Nov 21, 2011 · Viewed 22.8k times · Source

I get the following output:

Pushkin - 100500 
Gogol - 23 
Dostoyevsky - 9999

Which is the result of the following script:

for k in "${!authors[@]}"
do
    echo $k ' - ' ${authors["$k"]}
done   

All I want is to get the output like this:

Pushkin - 100500 
Dostoyevsky - 9999
Gogol - 23

which means that the keys in associative array should be sorted by value. Is there an easy method to do so?

Answer

Andrew Schulman picture Andrew Schulman · Nov 21, 2011

You can easily sort your output, in descending numerical order of the 3rd field:

for k in "${!authors[@]}"
do
    echo $k ' - ' ${authors["$k"]}
done |
sort -rn -k3

See sort(1) for more about the sort command. This just sorts output lines; I don't know of any way to sort an array directly in bash.

I also can't see how the above can give you names ("Pushkin" et al.) as array keys. In bash, array keys are always integers.