1.条件语句
第一步:创建passwd.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
}
}
第二步:执行如下命令
awk -f passwd.awk /etc/passwd
2.循环语句
第一步:创建for.awk,while.awk,dowhile.awd文件
BEGIN{
for(i=0;i<=100;i++)
{
sum=sum+i
}
print sum
}
BEGIN{
while(i<=100)
{
sum+=i
i++
}
print sum
}
BEGIN{
do
{
sum+=i
i++
}while(i<=100)
print sum
}
第二步:执行如下命令
awk -f for.awk
awk -f while.awk
awk -f dowhile.awk
3.综合
第一步:创建a.txt 文件
name chinese english math physocal
allen 90 78 65 69
zhang 70 75 78 90
xixi 90 95 87 92
jerry 89 60 89 76
第二步:创建sore.awk 文件
BEGIN{
printf "%-10s%-10s%-10s%-10s%-10s%-10s\n","name","chinese","english","math","physocal","avg"
}
{
total=$2+$3+$4+$5
avg=total/4
if (avg>90){
printf "%-10s%-10d%-10d%-10d%-10d%-0.2f\n",$1,$2,$3,$4,$5,avg
}
}
第三步:执行如下命令
awk -f sore.awk a.txt
效果如下
name chinese english math physocal avg
xixi 90 95 87 92 91.00