awk动作表达式中的算数运算符
awk动作表达式中的算数运算符
案例演示
使用awk计算/etc/services中的空白行数
awk 'BEGIN{sum=0}/^$/{++sum}END{print sum}' /etc/services
计算学生课程分数平均值,学生课程文件内容如下
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
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
awk 'BEGIN{num1=20;num2+=num1;print num1,num2}'
awk 'BEGIN{num1=20;num2=30;print num1+num2}'
awk 'BEGIN{num1=20;num2=30;print num1-num2}'
awk 'BEGIN{num1=20;num2=30;print num1*num2}'
awk 'BEGIN{num1=20;num2=30;print num1/num2}'
保留小数后两位
awk 'BEGIN{num1=20;num2=30;printf "%0.2f\n",num1/num2}'
awk 'BEGIN{num1=20;num2=3;printf "%0.2f\n",num1**num2}'
awk 'BEGIN{x=20;y=x++;print x,y}'
awk 'BEGIN{x=20;y=++x;print x,y}'
awk 'BEGIN{x=20;y=--x;print x,y}'
输出平均值
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
加上标题并格式化输出
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