網頁

2017年12月22日 星期五

UNIX入門課程1061_ex10

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

作業10: awk programming, associative array
如下例所示, 計算每個人的總和.
$ cat IN-7
# sample input file of exercise 7
                    # this is an blank line.
1234 Alice          # Alice wins 1234
999  Bob            # Bob wins 999
Alice 200           # Alice spends 200
Bob 100 Alice       # Bob loses 100 to Alice
4000 Bob 250 Carol  # Bod wins 4000 and loses 250 to Carol
3000 Carol 300      # Carol wins 3000 and spends 300

$ ./ex10.awk IN-7 Carol has 2950 Bob has 4649 Alice has 1134
$

解答:

#!/usr/bin/awk -f
BEGIN {
}
{
  sub(/#.*/,"") # change #.*  to ""
  for (i=1; i<=NF; i++) {
    if ($i ~ /^[0-9]/) {   #-----$1 is number
      money=$i
      if (i==2 || i==3) {  #-----money is spends or loses
        name=$(i-1)
        array[name]=array[name]-money
      }
    } else {               #-----$1 is name
      name=$i
      money=$(i-1)
      array[name]=array[name]+money
    }
  } #for END
}
 
END {
  for (name in array)
    printf("%s has %s\n", name, array[name])
}

執行結果:



沒有留言:

張貼留言