跟 C 语言类似,awk 中也可以用如 if, if else, if else if, :? 这些关键字进行判断,它们的语法也相似,如:if (conditional-expression)
action if (conditional-expression)
{
action1;
action2;
} if (conditional-expression)
action1
else
action2 if(conditional-expression1)
action1;
else if(conditional-expression2)
action2;
else if(conditional-expression3)
action3;
.
.
else
action n;
测试文本如下所示:$ cat if.txt
beyes 10000 90 98
admin 10001 99 64 72
tony 10002 45 32
tom 10003 12 34 87
lilei 10004 25 70 上面文本中,第 1 列是学生姓名,后面 3 列分别表示学生的 3 门功课成绩,其中有些学生不参加考试,从而没有分数记录。下面找出这些不参加考试的学生:$ awk '{
if ($3 == "" || $4 == "" || $5 == "")
print "missing score student is", $1;}' if.txt
missing score student is beyes
missing score student is tony
missing score student is lilei
如果学生的 3 门功课都大于等于 60 分,那么该考生考试合格,否则不合格,下面列出相关的信息:$ awk '{
> if ($3 >= 60 && $4 >= 60 && $5 >= 60)
> print $0, "=>", "Pass";
> else
> print $0, "=>", "Fail";
> }' if.txt
beyes 10000 90 98 => Fail
admin 10001 99 64 72 => Pass
tony 10002 45 32 => Fail
tom 10003 12 34 87 => Fail
lilei 10004 25 70 => Fail
如果学生的 3 门功课的平均分大于等于 60 的则为 A, 否则若是大于等于40的则为 B,否则若是大于等于 20 的则为 C,否则为 D 。脚本如下:
[Plain Text] 纯文本查看 复制代码 {
total = $3 + $4 + $5;
avg = total / 3;
if (avg >= 60) grade = "A";
else if (avg >= 40) grade = "B";
else if (avg >= 20) grade = "C";
else grade = "D";
print $0, "=>", grade;
}
运行输出:$ awk -f grade.awk if.txt
beyes 10000 90 98 => A
admin 10001 99 64 72 => A
tony 10002 45 32 => C
tom 10003 12 34 87 => B
lilei 10004 25 70 => C
下面的例子是 (?:) 的使用示例。在该示例中,在输出结果时,将原来的每 3 条合并成一行输出,每条记录由逗号分隔:$ awk '{ORS = NR%3 ? "," : "\n";} {print $0;} END {print "\n";}' if.txt
beyes 10000 90 98,admin 10001 99 64 72,tony 10002 45 32
tom 10003 12 34 87,lilei 10004 25 70, 可以将上面的语句简化一下:$ awk 'ORS = NR%3 ? "," : "\n"' if.txt
beyes 10000 90 98,admin 10001 99 64 72,tony 10002 45 32
tom 10003 12 34 87,lilei 10004 25 70, 注意,简化后的语句不能用 { } 括起来,否则不能看到输出。这是因为,如果用 { } 括起来,那么它将被看成一个 action ,而此时若是没有打印的 action (上调未简化命令中使用的 {print “\n";}语句),那么不会看到输出结果。而不给出 { } ,那么会采取默认的打印方式。参考:《awk 语法格式及工作方式概述》 中工作方式的第 6 条。 |