LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (http://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   bc,getopt and arrays in bash (http://www.linuxquestions.org/questions/linux-newbie-8/bc-getopt-and-arrays-in-bash-915381/)

congos 11-24-2011 04: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 04:53 PM

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

Code:

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:

Code:

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]}"

done


jhwilliams 11-24-2011 04:53 PM

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

Code:

#!/bin/bash

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]}
done

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


All times are GMT -5. The time now is 06:28 AM.