shell編程系列17--文本處理三劍客之awk動做中的表達式用法 awk動做表達式中的算數運算符awk動做中的表達式用法總結: 運算符 含義 + 加 - 減 * 乘 / 除 % 模 ^或** 乘方 ++x 在返回x變量以前,x變量加1 x++ 在返回x變量以後,x變量加1 --x 在返回x變量以前,x變量減1 x-- 在返回x變量以後,x變量減1 1、使用awk計算/etc/services中的空白行數量 awk 'BEGIN{sum=0}/^$/{++sum}END{print sum}' /etc/services 2、計算學生課程分數平均值,學生課程文件內容以下: Allen 80 90 96 98 Mike 93 98 92 91 Zhang 78 76 87 92 Jerry 86 89 68 92 Han 85 95 75 90 Li 78 88 98 100 # 代碼以下: [root@localhost shell]# awk 'BEGIN{printf "%-20s%-20s%-20s%-20s%-20s%-20s\n","Name","Chinese","English","Math","Physical","Average"}{sum=$2+$3+$4+$5;avg=sum/4}{printf "%-20s%-20d%-20d%-20d%-20d%-0.2f\n",$1,$2,$3,$4,$5,avg}' student.txt Name Chinese English Math Physical Average Allen 80 90 96 98 91.00 Mike 93 98 92 91 93.50 Zhang 78 76 87 92 83.25 Jerry 86 89 68 92 83.75 Han 85 95 75 90 86.25 Li 78 88 98 100 91.00 [root@localhost shell]# awk 'BEGIN{num1=20;num2+=num1;print num1,num2}' 20 20 [root@localhost shell]# awk 'BEGIN{num1=20;num2=30;print num1+num2}' 50 [root@localhost shell]# awk 'BEGIN{num1=20;num2=30;print num1-num2}' -10 [root@localhost shell]# awk 'BEGIN{num1=20;num2=30;print num1*num2}' 600 [root@localhost shell]# awk 'BEGIN{num1=20;num2=30;print num1/num2}' 0.666667 # 保留小數後兩位 [root@localhost shell]# awk 'BEGIN{num1=20;num2=30;printf "%0.2f\n",num1/num2}' 0.67 [root@localhost shell]# awk 'BEGIN{num1=20;num2=3;printf "%0.2f\n",num1**num2}' 8000.00 # 打印 [root@localhost shell]# awk 'BEGIN{num1=20;num2=3;printf "%0.2f\n",num1^num2}' 8000.00 # [root@localhost shell]# awk 'BEGIN{x=20;y=x++;print x,y}' 21 20 [root@localhost shell]# awk 'BEGIN{x=20;y=++x;print x,y}' 21 21 [root@localhost shell]# awk 'BEGIN{x=20;y=--x;print x,y}' 19 19 [root@localhost shell]# awk 'BEGIN{x=20;y=x--;print x,y}' 19 20 # 輸出平均值 [root@localhost shell]# cat student.txt Allen 80 90 96 98 Mike 93 98 92 91 Zhang 78 76 87 92 Jerry 86 89 68 92 Han 85 95 75 90 Li 78 88 98 100 [root@localhost shell]# awk '{total=$2+$3+$4+$5;AVG=total/4}{printf "%-8s%-5d%-5d%-5d%-8d%0.2f\n",$1,$2,$3,$4,$5,AVG}' student.txt Allen 80 90 96 98 91.00 Mike 93 98 92 91 93.50 Zhang 78 76 87 92 83.25 Jerry 86 89 68 92 83.75 Han 85 95 75 90 86.25 Li 78 88 98 100 91.00 # 加上標題並格式化輸出 [root@localhost shell]# awk 'BEGIN{printf "%-10s%-10s%-10s%-10s%-10s%-10s\n","name","Yuwen","math","English","Pysical","Average"}{total=$2+$3+$4+$5;AVG=total/4}{printf "%-10s%-10d%-10d%-10d%-10d%-10.2f\n",$1,$2,$3,$4,$5,AVG}' student.txt name Yuwen math English Pysical Average Allen 80 90 96 98 91.00 Mike 93 98 92 91 93.50 Zhang 78 76 87 92 83.25 Jerry 86 89 68 92 83.75 Han 85 95 75 90 86.25 Li 78 88 98 100 91.00