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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With