标签:mamicode 数值 cal 图片 用户 信息 表达 div highlight
条件语句
if(条件表达式) 动作1 else if(条件表达式) 动作2 else 动作3
循环语句:
while循环: while(条件表达式) 动作 do while循环: do 动作 while(条件表达式) for循环: for(初始化计数器;计数器测试;计数器变更) 动作
以:为分隔符,只打印/etc/passwd中第3个字段的数值在50-100范围内的行信息
awk ‘BEGIN{FS=":"}{if($3>50 && $3<100) print $0}‘ passwd
if.awk
BEGIN{ FS=":" } { if($3<50) { printf "%-20s%-20s%-10d\n","UID<50",$1,$3 } else if ($3>50 && $3<100) { printf "%-20s%-20s%-10d\n","50<UID<100",$1,$3 } else { printf "%-20s%-20s%-10d\n","UID>100",$1,$3 } }
输出 以 UID 以50位为分界点的用户,-f 将条件表达式写到文本中读取
awk -f if.awk passwd
计算下列每个同学的平均分数,并且只打印平均分数大于90的同学姓名和分数信息
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
加入条件判断,如果平均分数大于90才打印
awk ‘BEGIN{printf "%-20s%-20s%-20s%-20s%-20s%-20s\n","Name","Chinese","English","Math","Physical","Average"}{sum=$2+$3+$4+$5;avg=sum/4}{if(avg>90) printf "%-20s%-20d%-20d%-20d%-20d%-0.2f\n",$1,$2,$3,$4,$5,avg}‘ student.txt
计算1+2+3+4+...+100的和,请使用while、do while、for三种循环方式实现
通过读取文件的方式载入awk的条件
add_while.awk
BEGIN{ while(i<=100) { # 一个变量不赋值,默认为0或者空 sum+=i i++ } print sum }
do while循环
awk -f add_dowhile.awk
for循环
add_for.awk
BEGIN{ for(i=0;i<=100;i++) { sum+=i } print sum }
标签:mamicode 数值 cal 图片 用户 信息 表达 div highlight
原文地址:https://www.cnblogs.com/crazymagic/p/11154717.html