Wednesday, August 6, 2014

[Bash] sum numbers in an array

#!/bin/bash
# sum all/part the numbers in an array using bc
# usage:
#           mysum number-array [index0 index1]
#           Note: the index starts from 1
# e.g.,
#      myA=(34 23 32.5 33.2 25)
#      mysum "${myA[*]}" ==> 147.7
#      mysum "${myA[*]}" 1 2 ==> 57
#      mysum "${myA[*]}" 2 4 ==> 88.7
#      mysum "12 23 12" ==> 47
#
# http://scriptdemo.blogspot.com

isDebug=0
if [ $# -eq 0 ]; then
   sed -n '3,8p' `which mysum`
   exit
else
  myA=($1)
  [ ${isDebug} -eq 1 ] && echo ${myA[*]}
  [ ${isDebug} -eq 1 ] && echo "narg: $#"
  if [ $# -eq 1 ]; then
     if [ ${isDebug} -eq 1 ]; then
        echo "sum: `echo ${myA[*]} | sed 's/\ /+/g' | bc -l`"
     else
        echo "`echo ${myA[*]} | sed 's/\ /+/g' | bc -l`"
     fi
  elif [ $# -eq 2 ]; then
     ind0=`expr $2 - 1`
     nC=`expr ${#myA[*]} - ${ind0}`
     if [ ${isDebug} -eq 1 ]; then
        echo "sum: `echo ${myA[*]:${ind0}:${nC}} | sed 's/\ /+/g' | bc -l`"
     else
        echo "`echo ${myA[*]:${ind0}:${nC}} | sed 's/\ /+/g' | bc -l`"
     fi
  elif [ $# -eq 3 ]; then
     ind0=`expr $2 - 1`
     nC=`expr $3 - ${ind0}`
     if [ ${isDebug} -eq 1 ]; then
        echo "sum: `echo ${myA[*]:${ind0}:${nC}} | sed 's/\ /+/g' | bc -l`"
     else
        echo "`echo ${myA[*]:${ind0}:${nC}} | sed 's/\ /+/g' | bc -l`"
     fi
  fi

No comments:

ShowCalendar