歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux基礎 >> Linux教程 >> AWK使用練習

AWK使用練習

日期:2017/2/28 14:56:19   编辑:Linux教程

環境
RedHat Linux 9 + VWWare 8.0 + SSH 3.2.9

任務

下面的文本中包含名字、電話和為黨派運動捐款的數額。
名字:電話:1月捐款情況:2月捐款情況:3月捐款情況
Mike Harrington :(510) 548-1278:250:100:175
Christian Dobbins:(408) 538-2358:155:90:201
Susan Dalsass:(206) 654-6279:250:60:50
Archie McNichol:(206) 548-1348:250:100:175
Jody Savage: (206) 548-1278:15:188:150
Guy Quigley:(916) 343-6410:250: 100:175
Dan Savage:(406) 298-7744:450:300:275
NancyMcNeil:(206) 548-1278:250:80:75
John Goldenrod:(916) 348-4278:250:100:175
Chet Main:(510) 548-5258:50:95:135
Tom Savage:(408) 926-3456:250:168:200
Elizabeth Stachelin:(916) 440-1763:175:75:300
使用你能用到的任何linux命令腳本產生一個如下的報告,注意,報告中的summery包含對於捐款情況的一些統計信息。

解決

#!/bin/bash
#filename:test.sh
sourcename=$1
echo "$sourcename"
sed -i "s/: /:/g" sourcename
echo " ***FIRST QUARTERLY REPORT **** "
echo " ***CAMPAIGN 2000 CONTRIBUTIONS ***"
echo "-------------------------------------------------------------------"
echo " NAME PHONE JAN| Feb| Mar| Total Danated "
echo "-------------------------------------------------------------------"
awk -F: '{printf( "%-20s%12s%5d%5d%5d\t%5d\n",$1,$2,$3,$4,$5,$3+$4+$5) } ' linux2.txt
echo "-------------------------------------------------------------------"
echo " SUMMARY "
echo "-------------------------------------------------------------------"
awk -F: 'BEGIN{sum=0;total=0} {total=$3+$4+$5;sum+=total} END {
printf("The campaign received a total of $%d for this quartor\n",sum)
}' linux2.txt
awk -F: 'BEGIN{average=0;i=0;total=0;sum=0} {total=$3+$4+$5;sum+=total;i++}
END {average=sum/i;printf("The average donation for the %d contributors was $%.2f.\n",i,average) }' linux2.txt
awk -F: 'BEGIN{highest=0;sum=0;total=0;name} {
total=$3+$4+$5;if(total> highest) {highest=total;name=$1}} END {
printf("The highest total contribution was $%.2f made by %s\n",highest,name) }' linux2.txt

echo " ***THANKS Dan*** "
echo "The following people donated over \$500 to the campaign "
echo "They are eligible for the quarterly drawing!! "
echo "Listed are their names (sorted by last names) and phone numbers: "
awk -F: 'BEGIN{ OFS="--";biaozhun=500;total=0} {
$1="\t"$1;total=$3+$4+$5;if(total>biaozhun) print $1,$2 | "sort -k 2" }' linux2.txt
echo " Thanks to all of you for your continued support!! "

運行效果

參考資料

Linux awk 內置函數詳細介紹(實例) http://www.linuxidc.com/Linux/2012-11/74816.htm

Copyright © Linux教程網 All Rights Reserved