How to sort an associative array and retain the keys?
8,789
Assuming your keys don't contain colons or newlines and your values don't contain newlines:
for key in "${!MYARRAY[@]}"; do
printf '%s:%s\n' "$key" "${MYARRAY[$key]}"
done | sort -t : -k 2n
If you need to arrange the key in the order given by the values, read back the output:
IFS=$'\n'; set -f
sorted_keys=($(
for key in "${!MYARRAY[@]}"; do
printf '%s:%s\n' "$key" "${MYARRAY[$key]}"
done | sort -t : -k 2n | sed 's/:.*//'))
unset IFS; set +f
Related videos on Youtube
![dibs](https://i.stack.imgur.com/GoHNy.png?s=256&g=1)
Author by
dibs
Updated on September 18, 2022Comments
-
dibs almost 2 years
I have an array with filenames as keys and a numerical value as values.
MYARRAY[00001.jpg] = 31 MYARRAY[00002.jpg] = 200 MYARRAY[00003.jpg] = 98
I need to sort them so they are ordered by value. Which I am doing with
IFS=$'\n' SORTED=($(sort <<<"${MYARRAY[*]}"))
However I lose the keys and just have numerical ones now.
Desired output would be
00001.jpg:31 00003.jpg:98 00002.jpg:200
How can I retain the keys in such a sort?
-
dibs over 9 yearsI can't seem to get useful output with this so far. Could you humour me a bit. What does the sed stuff do?
-
Gilles 'SO- stop being evil' over 9 years@dibs The for loop prints out lines like
00001.jpg:31
. The sed command removes the part after the colon. I fixed an error that causedsorted_keys
to be a single string containing all the names, instead of an array as intended. -
pdolinaj about 6 yearsHow would I modify this function to display for example only the TOP 2 file names, without the count?
-
von spotz about 3 years@Gilles'SO-stopbeingevil' Hello, could you kindly explain what the
-k 2n
option means? Best wishes, von Spotz -
Gilles 'SO- stop being evil' about 3 years@vonspotz
-k
sets the sort key, i.e. what part of each line to use to sort.2
means to start at the second field.n
means to use numerical order rather than lexicographic order (so9
sorts before10
). -
von spotz about 3 years@Gilles'SO-stopbeingevil' Thank you very much!