Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash associative array sorting by value

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?

like image 704
Graf Avatar asked Nov 21 '11 18:11

Graf


People also ask

How do you sort an associative array in bash?

The best way to sort a bash associative array by VALUE is to NOT sort it. Instead, get the list of VALUE:::KEYS, sort that list into a new KEY LIST, and iterate through the list. Show activity on this post. Show activity on this post.


1 Answers

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.

like image 168
Andrew Schulman Avatar answered Nov 07 '22 05:11

Andrew Schulman