1.单条语句
语法:
if(conditional-expression ) action
if 是关键字
conditional-expression 是要检测的条件表达式
action 是要执行的语句
2.多条语句
如果要执行多条语句,需要把他们放在{ } 中,每个语句之间必须用分号或换行符分开,如下所示.
语法:
if (conditional-expression) { action1; action2; }如果条件为真,{ } 中的语句会依次执行。当所有语句执行完后,awk 会继续执行后面的语句。
注意:与具体的花括号后面不能加分号。
实例1:打印数量小于等于 5 的所有商品
[root@localhost ~]# !cat cat items.txt 101,HD Camcorder,Video,210,10 102,Refrigerator,Appliance,850,2 103,MP3 Player,Audio,270,15 104,Tennis Racket,Sports,190,20 105,Laser Printer,Office,475,5 [root@localhost ~]# awk -F, '{ if($5<=5) print "Only",$5,"qty of",$2 "is available"}' items.txt Only 2 qty of Refrigeratoris available Only 5 qty of Laser Printeris available实例2:打印价钱在 500 至 100,并且总数不超过 5 的商品
[root@localhost ~]# awk -F, '{ if (($4 >= 500 && $4<= 1000) && ($5 <= 5)) print "Only",$5,"qty of",$2,"is available" }' items.txt Only 2 qty of Refrigerator is available 二、if else 结构在 if else 结构中, 还可以指定判断条件为 false 时要执行的语句。 下面的语法中,如果条件 为 true,那么执行 action1,如果条件为 false,则执行 action2
语法:
if (conditional-expression) action1 else action2此外, awk 还有个条件操作符( ? : ), 和 C 语言的三元操作符等价。
和 if-else 结构相同,如果 codintional-expresion 是 true,执行 action1,否则执行 action2。
三元操作符:
codintional-expression ? action1 : action2 ;实例1:如果商品数量不大于 5,打印”Buy More”,否则打印商品数量
[root@localhost ~]# cat if.awk BEGIN { FS=","; } { if( $5 <= 5) print "Buy More: Order",$2,"immediately!" else print "Shell More: Give discount on",$2,"immediately!" } [root@localhost ~]# cat items.txt 101,HD Camcorder,Video,210,10 102,Refrigerator,Appliance,850,2 103,MP3 Player,Audio,270,15 104,Tennis Racket,Sports,190,20 105,Laser Printer,Office,475,5 [root@localhost ~]# awk -f if.awk items.txt Shell More: Give discount on HD Camcorder immediately! Buy More: Order Refrigerator immediately! Shell More: Give discount on MP3 Player immediately! Shell More: Give discount on Tennis Racket immediately! Buy More: Order Laser Printer immediately!实例2:用三元操作符,把 items.txt 文件中的每两行都以逗号分隔合并起来
[root@localhost ~]# cat items.txt 101,HD Camcorder,Video,210,10 102,Refrigerator,Appliance,850,2 103,MP3 Player,Audio,270,15 104,Tennis Racket,Sports,190,20 105,Laser Printer,Office,475,5 [root@localhost ~]# awk 'ORS=NR%2?",":"\n"' items.txt 101,HD Camcorder,Video,210,10,102,Refrigerator,Appliance,850,2 103,MP3 Player,Audio,270,15,104,Tennis Racket,Sports,190,20 105,Laser Printer,Office,475,5,[root@localhost ~]#相同于:
[root@localhost ~]# awk '{ if (NR %2 ==0) ORS = "\n";else ORS = ",";print}' items.txt 101,HD Camcorder,Video,210,10,102,Refrigerator,Appliance,850,2 103,MP3 Player,Audio,270,15,104,Tennis Racket,Sports,190,20 105,Laser Printer,Office,475,5,[root@localhost ~]# 二、while 循环语法:
while (codition) Actions
while 是 awk 的关键字
condition 是条件表达式
actions 是循环体,如果有多条语句,必须放在{ }中
while首先检查 condtion,如果是 true,执行 actions,执行完后,再次检查 condition,如果是 true, 再次执行 actions,直到 condition 为 false 时,退出循环。
实例1:
[root@localhost ~]# awk 'BEGIN { while(count++<50) string=string "x"; print string}' xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx