How to find a key based on value in dictionary?
#!/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.
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.