Home > Software engineering >  Bash sorting the values of Map in descending order
Bash sorting the values of Map in descending order

Time:01-06

I have declared a map in bash like the following

declare -A myMap
myMap=( [A:B:C:D]=813.0 [P:Q:R:S]=2346957.02 [W:X:Y:Z]=53831.93 [E:F:G:H]=113770.0)

I want to split the string in Key having delimiter (:) and get the output in descending order of value like this

P - Q - R - S - 2346957.02    
E - F - G - H - 113770.0    
W - X - Y - Z - 53831.93    
A - B - C - D - 813.0

The code I am trying is the following

for k in "${!myMap[@]}"    
do    
  arrIN=(${k//:/ })    
  echo ${arrIN[0]} ' - ' ${arrIN[1]} ' - ' ${arrIN[2]} ' - ' ${arrIN[3]} ' - ' ${myMap["$k"]}    
done | sort ${myMap["$k"]}

But the output using my code is this

E - F - G - H - 113770.0    
W - X - Y - Z - 53831.93    
P - Q - R - S - 2346957.02    
A - B - C - D - 813.0

Is there an easy way to achieve this?

CodePudding user response:

If you print the original key and the value, sort by the second column (k2), numeric reverse.

#! /bin/bash
declare -A myMap
myMap=( [A:B:C:D]=813.0 [P:Q:R:S]=2346957.02 [W:X:Y:Z]=53831.93 [E:F:G:H]=113770.0)

for k in ${!myMap[@]} ; do
    echo $k ${myMap[$k]}
done | sort -rnk2 | sed 's/[: ]/ - /g'

If you split the key, you need to sort by the ninth column:

for k in "${!myMap[@]}" ; do    
    arrIN=(${k//:/ })
    echo ${arrIN[0]} - ${arrIN[1]} - ${arrIN[2]} - ${arrIN[3]} - ${myMap[$k]}
done | sort -nrk9

CodePudding user response:

Alternate method using the file name globbing to sort keys.

#!/usr/bin/env bash

declare -A myMap
myMap=( [A:B:C:D]=813.0 [P:Q:R:S]=2346957.02 [W:X:Y:Z]=53831.93 [E:F:G:H]=113770.0)

tmpDir=
trap 'rm -fr "$tmpDir"' EXIT INT
tmpDir=$(mktemp -d)

myKeys=("${!myMap[@]}")

# Create a file per key in the temp directory
touch "${myKeys[@]/#/$tmpDir/}"

# Load keys from temp directory benefiting from auto sorting
myKeys=("$tmpDir/"*)

# Strip file path from keys
myKeys=("${myKeys[@]##*/}")

# Iterate keys in reverse order
for (( i=${#myKeys[@]}-1; i>=0; i-- )); do

  k=${myKeys[i]}

  # Split key by :
  IFS=: read -ra ka <<<"$k"

  # Get corresponding value
  v=${myMap[$k]}

  # Print joined key elements with " - " followed by value
  printf '%s%s%s%s%s\n' "${ka[@]/%/ - }" "$v"
done
  •  Tags:  
  • Related