-   Linux - Newbie (
-   -   bc,getopt and arrays in bash (

congos 11-24-2011 03:17 PM

bc,getopt and arrays in bash
trying to sum elements in an array using bc and getopt,i have a file with names and thier vaules if the names appears 3 times i should multiply its value with 3 then find the sum of all the elements together

cat foo.txt

max 2.3
henry 3
fransis 4.5
max 2.3
henry 3
max 2.3

it should show on the terminal
max 6.9
henry 6
fransis 4.5

and so on
im trying to avoid awk

David the H. 11-24-2011 03:53 PM

Why would you want to avoid awk? This is a perfect application for it:


awk '{ array[$1] += $2 } END{ for ( i in array ) { print i , array[i] } }' file
I also don't understand your reference to getopt. What does that have to do with it?

Anyway, using the same basic logic as the above awk command, and bash v4's associative arrays:


declare -A array

while read name value; do

    array[$name]=$( echo "${array[$name]:-0} + $value" | bc )

done < file

for name in "${!array[@]}"; do

    echo "$name ${array[$name]}"


jhwilliams 11-24-2011 03:53 PM

This Bash 4.0+ script using an associative array seems to work. Could probably be simpler.



declare -A map

while read line; do
    key=${line%% *}
    value=${line##* }
    [ -z "${map[$key]}" ] && map[$key]=0
    map[$key]=$(bc <<< "${map[$key]} + $value")
done < $@

for person in ${!map[*]}; do
    echo -e $person\: ${map[$person]}

EDIT: Oops, yea, David's is cleaner.

All times are GMT -5. The time now is 12:15 PM.