作者/来源:yixinu.com
栏目:运维/编程
日期:2012-04-05 11:04:44
example:
过虑用户ID>=500账户并做统计
[root@desktop10 0405]# gawk -F: '{ if($3>=500){print $1,$3; count++}} END{print count}' /etc/passwd nfsnobody 65534 student 500 visitor 501 3 [root@desktop10 0405]#
system函数
example:
#!/bin/gawk /^[^#:]/ { res=system("ping -c2 " $1 "&>/dev/null" ); #函数返回值由res接收 if(res==0){ print $1 " is online" }else{ print $1 " is down" } }
while循环
example: 打印passwd 列变成 行
[root@desktop10 0405]# gawk -F: '{print $0,"nn=========================;";lie=1;while(lie<=NF){print $lie; lie++} print "nn" }' /etc/passwd
example:
#!/bin/gawk { print NR,"======================nn"; for(lie=1;lie<=NF;lie++){ print $lie; } print "nn"; }
1 ====================== root x 0 0 root /root /bin/bash 2 ====================== bin x 1 1 bin /bin /sbin/nologin ....
example:
[root@desktop10 0405]# gawk -F: '{print NR,"=====================n"; for(lie=1;lie<=NF;lie++){print lie,":",$lie;}print "n"}' /etc/passwd
数组
example:
[root@desktop10 0405]# cat file tom 4424 54366 mary 5446 2488 bill 168814 58744 tom 4424 100 [root@desktop10 0405]# cat file | gawk '{names[$1]=$3}; END{ print names["tom"] }' 100 [root@desktop10 0405]#
[root@desktop10 0405]# cat file | gawk '{names[$1]+=$3}; END{ print names["tom"] }' 54466
example: 用于数组的for循环 for(索引 in 数组){ 代码 }
[root@desktop10 0405]# cat file | gawk '{names[$1]+=$3}; END{ for(name in names){ print name,names[name] } }' bill 58744 tom 54466 mary 2488
example:
[root@desktop10 0405]# cat ./test3.awk #!/bin/gawk { names[$1]+=$3 }; END{ for(name in names){ print name,names[name] } }
nextexit
example:
exit并不会绕过END段,所以通过 exits变量来判断 当前代码是否成功执行
#!/bin/awk BEGIN{getline USER < "-"} { if($1 ~ USER){ exist=1; exit; } } END{ if(exist){ exit(0); }else{ exit(-1); } } [root@bogon ~]# echo "root" | gawk -F: -f awk3.awk ./passwd [root@bogon ~]# echo $? 0 [root@bogon ~]# echo "rootssss" | gawk -F: -f awk3.awk ./passwd [root@bogon ~]# echo $? 255 [root@bogon ~]#
example: next的作用
#!/bin/awk BEGIN{getline USER < "-"} { i=1; while(i<NF){ print i; if($i ~ USER){ print "======",NR,"======"; next; } i++ } print NR,"+++++" } [root@bogon ~]# echo "ftp" | gawk -F: -f awk4.awk ./passwd ………… 12 +++++ 1 2 3 4 5 6 13 +++++ 1 ====== 14 ====== #next使程序路过了循环,14行并没有输出,如果上面代码换成exit,则在该行停止循环 1 2 3 4 5 6 15 +++++ …………
处理命令行参数
ARGC代表参数的总数
ARGV 数组,保存输入的参数
example:
[root@bogon ~]# cat awk6.awk #!/bin/awk BEGIN{ for(pos=0;pos<ARGC;pos++){ print ARGV[pos]; } } [root@bogon ~]# gawk -f awk6.awk aa bb cc gawk aa bb cc [root@bogon ~]#