Skip to main content
fixed splitting of sorted_keys
Source Link
Gilles 'SO- stop being evil'
  • 865.3k
  • 205
  • 1.8k
  • 2.3k

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=:;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

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=:; 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

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
Source Link
Gilles 'SO- stop being evil'
  • 865.3k
  • 205
  • 1.8k
  • 2.3k

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=:; 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