網頁

顯示具有 awk 標籤的文章。 顯示所有文章
顯示具有 awk 標籤的文章。 顯示所有文章

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

執行結果:



2016年12月30日 星期五

UNIX入門課程1051_ex9

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

作業九: figure out the average for each user(awk programming)
與作業七相同, 但改用 awk 來作. input 的 data 中的 name 可能會重複出現.
$ cat ex9-k1
klim 10 20 milk 199 joe 20
# klim is appeared again!
oak 100 red 200 10 klim 30
joe 199  marry 20 julie 2000  #joe joe
$ ./ex9.awk < ex9-k1
klim = 20.00
milk = 199.00
oak = 100.00
red = 105.00
joe = 109.50
marry = 20.00
julie = 2000.00
$

解答:
#!/usr/bin/awk -f
BEGIN {
}
{
  sub(/#.*/,"")
  if ( $0 != "" ) {
    for (i=1; i<=NF; i++) {
      if ( $i ~ /[a-z]/ ) {  # $1 is name
        name=$i
      }
      else {                 # $1 is number
        array[name]=array[name]+$i
        num_count[name]=num_count[name]+1
      }
    } #for i END
  } #if END
}
END {
for (i in array)
  printf("%s = %.2f\n",i, array[i]/num_count[i])
}
執行結果:


 

2016年12月23日 星期五

UNIX入門課程1051_ex8

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

作業八: figure out the average and the max three (awk programming)
跟作業六一樣, 但改用 awk 來寫.
請全用 awk 來寫, 不要混用 sh 或 sed.
請寫成一個 script file, 並設定成可執行.
input 的 data 內可能有 comment.

$ cat k1
10 20 30 #this is a comment
8 7
# this is also a comment
2
$ ./ex8.awk k1
the max three are: 30 20 10
the average is   : 12.83
$

解答:

#!/usr/bin/awk -f
BEGIN {
}
{
  sub(/#.*/ , "")
  if ( $0 != "" ) {
    for (i=1; i<=NF; i++) {
      num[count]=$i
      sum+=$i
      count++
    } #for END
  } #if END
}
 
END {
  asort(num) #sort num[] array
  printf("the max three are: %d %d %d\n",num[count],num[count-1],num[count-2])
  printf("the average is   : %.2f\n",sum/count)
} 

注意:程式中asort函數在GNU awk 3.1才有提供


執行結果: