網頁

2016年12月16日 星期五

UNIX入門課程1051_ex7

http://erdos.csie.ncnu.edu.tw/~klim/unix-intro/unix-intro-1051.html

作業七: figure out the average for each user(sh programming)
$ cat ex7-k1
klim 10 20 30 milk 199 
oak 100 red 200 10
joe 199 20 marry 20 julie 2000
$ ./ex7.sh < ex7-k1
klim = 20.00
milk = 199.00
oak = 100.00
red = 105.00
joe = 109.50
marry = 20.00
julie = 2000.00
$

解答:

#!/bin/bash
function AVERAGE () {
  avg=$(echo "scale=2; $2/$3" | bc)
  echo "$1 = $avg"
}
function DATA () {
  #if [[ $1 != [0-9]*  &&  -n $1 ]]; then
  if [[ $1 =~ [a-z]+  &&  -n $1 ]]; then
    #echo "name:$1"
    name[index]=$1
    let index+=3
    sum=0
    count=0
  else
    let sum=sum+$1
    if [ ! -z $1 ]; then
      let count++
    fi
      name[index-2]=$sum
      name[index-1]=$count
  fi 
}
index=1
while read line
do
  if [ "$line" != "" ]; then
    set $(echo $line)
    field=$#    #*** $# is field count
    for ((i=1; i<=field; i++))
    do
      #echo "data:$1"
      DATA $1
      shift
    done
  fi
done #while END
for ((i=1; i<=index-3; i=i+3))
do
  #echo "Name:${name[$i]}  sum=${name[i+1]}  count=${name[i+2]}"
  AVERAGE ${name[$i]} ${name[i+1]} ${name[i+2]}
done

執行結果:




沒有留言:

張貼留言