awk 表达式
Posted crazymagic
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了awk 表达式相关的知识,希望对你有一定的参考价值。
awk动作表达式中的算数运算符
awk动作表达式中的算数运算符
案例演示
使用awk计算/etc/services中的空白行数
awk ‘BEGINsum=0/^$/++sumENDprint 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 ‘BEGINprintf "%-20s%-20s%-20s%-20s%-20s%-20s\\n","Name","Chinese","English","Math","Physical","Average"sum=$2+$3+$4+$5;avg=sum/4printf "%-20s%-20d%-20d%-20d%-20d%-0.2f\\n",$1,$2,$3,$4,$5,avg‘ student.txt
awk ‘BEGINnum1=20;num2+=num1;print num1,num2‘
awk ‘BEGINnum1=20;num2=30;print num1+num2‘
awk ‘BEGINnum1=20;num2=30;print num1-num2‘
awk ‘BEGINnum1=20;num2=30;print num1*num2‘
awk ‘BEGINnum1=20;num2=30;print num1/num2‘
保留小数后两位
awk ‘BEGINnum1=20;num2=30;printf "%0.2f\\n",num1/num2‘
awk ‘BEGINnum1=20;num2=3;printf "%0.2f\\n",num1**num2‘
awk ‘BEGINx=20;y=x++;print x,y‘
awk ‘BEGINx=20;y=++x;print x,y‘
awk ‘BEGINx=20;y=--x;print x,y‘
输出平均值
awk ‘total=$2+$3+$4+$5;AVG=total/4printf "%-8s%-5d%-5d%-5d%-8d%0.2f\\n",$1,$2,$3,$4,$5,AVG‘ student.txt
加上标题并格式化输出
awk ‘BEGINprintf "%-10s%-10s%-10s%-10s%-10s%-10s\\n","name","Yuwen","math","English","Pysical","Average"total=$2+$3+$4+$5;AVG=total/4printf "%-10s%-10d%-10d%-10d%-10d%-10.2f\\n",$1,$2,$3,$4,$5,AVG‘ student.txt
以上是关于awk 表达式的主要内容,如果未能解决你的问题,请参考以下文章