Score:0

How to find a key based on value in dictionary?

us flag
#!/bin/bash
cd /pg
declare -A arr
file=`ls -l |awk '{print $9}'`
#declare -A  test_dict
for i in $file
do
  #if [[ "$one" -eq "1" ]]; then
  one=`cat /pg/$i | wc -l`
  if [[ "$one" -eq "1" ]]; then
     key=$(awk 'NR==1{print $7}' "/pg/$i")
     value=$(awk 'NR==1{print $8}' "/pg/$i")
     #echo $key
     #echo $value
     arr["$key"]=$value
  else
     key=$(awk 'NR==1{print $7}' "/pg/$i")
     value=$(awk 'NR==1{print $8}' "/pg/$i")
     value1=$(awk 'NR==2{print $8}' "/pg/$i")
     c=$(($value+$value1))
     arr["$key"]=$c
  fi
done
echo ${arr[@]}
max=0
for j in "${arr[@]}";do
    if (( $j > max));then
            max=$j
    fi
done
echo "max:$max"
echo  "${!arr[@]}"

From the above code I'm appending "key","values" to the dictionary and getting maxium value, so now I need to print the "key" based on "max" value. value's are "120 60 75 60" maxium values is "120" key's are "hari azureuser cnu root" expecting out put is : hari becasue maxium value[120] came from "hari". Please help me to achieve the same.

Artur Meinild avatar
vn flag
This looks like a generic programming question that really hasn't got anything to do with Ubuntu. Please search for similar questions at [so].
Score:1
in flag

Loop over keys:

max=0
for k in "${!arr[@]}";do
    if (( ${arr["$k"]} > max));then
            max="${arr["$k"]}"
            max_key="$k"
    fi
done
echo "$max_key"

However, there are better options to do such things than using a bash script.

Haridvpsk avatar
us flag
Hi Mr. pLumo The above solution works for me .Thanks a lot!.
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.