首页 > 代码库 > awk控制语句

awk控制语句

一、awk控制语句类型

{ statements;… } 组合语句

if(condition) {statements;…} 

if(condition) {statements;…} else {statements;…}

while(conditon) {statments;…}

do {statements;…} while(condition)

for(expr1;expr2;expr3) {statements;…}

break

continue

delete array[index]

delete array

exit


二、if-else语句

语法:if(condition) statement [else statement]

if(condition1){statement1}else if(condition2){statement2} else{statement3}

使用场景:对awk取得的整行或某个字段做条件判断

示例:

awk -F: ‘{if($3>=1000)print $1,$3}‘ /etc/passwd

awk -F: ‘{if($NF=="/bin/bash") print $1}‘ /etc/passwd

awk ‘{if(NF>5) print $0}‘ /etc/fstab

awk -F: ‘{if($3>=1000) {printf "Common user: %s\n",$1} else {printf "root or Sysuser: %s\n",$1}}‘ /etc/passwd

awk -F: ‘{if($3>=1000) printf "Common user: %s\n",$1;else printf "root or Sysuser: %s\n",$1}‘ /etc/passwd

df -h|awk -F% ‘/^\/dev/{print $1}‘|awk ‘$NF>=80{print $1,$5}‘

awk ‘BEGIN{ test=100;if(test>90){print "very good"} else if(test>60){ print "good"}else{print "no pass"}}‘


三、while循环

语法:while(condition){statement;…}

条件“真”,进入循环;条件“假”,退出循环

使用场景:

对一行内的多个字段逐一类似处理时使用

对数组中的各元素逐一处理时使用

示例:

awk ‘/^[[:space:]]*linux16/{i=1;while(i<=NF) {print $i,length($i); i++}}‘ /etc/grub2.cfg

awk ‘/^[[:space:]]*linux16/{i=1;while(i<=NF) {if(length($i)>=10) {print $i,length($i)}; i++}}‘ /etc/grub2.cfg


四、do-while循环

语法:do {statement;…}while(condition)

意义:无论真假,至少执行一次循环体

示例:

awk ‘BEGIN{ total=0;i=0;do{ 

total+=i;i++;}while(i<=100);print total}‘

思考:下面两语句有何不同?

awk  ‘BEGIN{i=0;print ++i,i}‘

awk  ‘BEGIN{i=0;print i++,i}‘


五、for循环

语法:for(expr1;expr2;expr3) {statement;…}

常见用法:

for(variable assignment;condition;iteration process) {for-body}

特殊用法:能够遍历数组中的元素;

语法:for(var in array) {for-body}

示例:

awk ‘/^[[:space:]]*linux16/{for(i=1;i<=NF;i++) {print $i,length($i)}}‘ /etc/grub2.cfg


性能比较

time (awk ‘BEGIN{ total=0;for(i=0;i<=10000;i++){total+=i;};print total;}‘)

time (total=0;for i in {1..10000};do total=$(($total+i));done;echo $total)

time (for ((i=0;i<=10000;i++));do let total+=i;done;echo $total)


六、switch语句

语法:switch(expression) {case VALUE1 or /REGEXP/: 

statement; case VALUE2 or /REGEXP2/: statement; ...; default: statement}

break和continue

awk ‘BEGIN{sum=0;for(i=1;i<=100;i++) {if(i%2==0){continue}sum+=i}print sum}‘

awk ‘BEGIN{sum=0;for(i=1;i<=100;i++) {if(i==66){break}sum+=i}print sum}‘

break [n]

continue [n]

next:

提前结束对本行处理而直接进入下一行处理(awk自身循环)

awk -F: ‘{if($3%2!=0) next; print $1,$3}‘ /etc/passwd

本文出自 “爱情防火墙” 博客,请务必保留此出处http://183530300.blog.51cto.com/894387/1854715

awk控制语句