AWK中两种循环语句:if-else 和 while
控制流语句:
1.if-else
求总数,平均值:
[root@monitor awkdir]# awk '$3>6 {n = n + 1;pay = pay + $2*$3}END{print n,pay/n}' emp.txt
4 84.375
语句:
awk '$3 > 6 {n = n + 1 ;pay = pay + $2 * $3}
END {if (n > 0)
print n,"employees,total pay is",pay,
"average",pay/n
else
print "no employees are paid more than $6/hour"
}
' emp.txt
实例:
[root@monitor awkdir]# awk '$3 > 6 {n = n + 1 ;pay = pay + $2 * $3}
> END {if (n > 0)
> print n,"employees,total pay is",pay,
> "average",pay/n
> else
> print "no employees are paid more than $6/hour"
> }
> ' emp.txt
4 employees,total pay is 337.5 average 84.375
2.while
语句:
awk '{
i = 1
while (i <=$3)
{printf(" %.3f
",$1 * (1 + $2) ^ i)
i = i + 1
}
}' w.txt
--
[root@monitor awkdir]# awk '
> {i = 1
> while (i<=$3){
> printf(" %.2f
",$1 * (1 + $2) ^ i)
> i = i + 1
> }
> }' w.txt
1060.00
1123.60
1191.02
1262.48
1338.23
1120.00
1254.40
1404.93
1573.52
1762.34
1973.82
数组:
[root@monitor awkdir]# awk '{line[NR] = $0}END{i = NR ;while (i>0) {print line[i] ;i = i - 1}}' emp.txt
Susie 4.25 18
Mary 5.50 22
Mark 5.00 20
Kathy 4.00 10
Dan 3.75 0
Beth 4.00 0
[root@monitor awkdir]# awk '{line[NR] = $0}END{i = NR ;while (i>3) {print line[i] ;i = i - 1}}' emp.txt
Susie 4.25 18
Mary 5.50 22
Mark 5.00 20