后再显示该行(记录)。 awk ‘{$7 %= 3; print $7}’ file 将第7域被3除,并将余数赋给第7域再打印。 11、 awk ‘/tom/ {wage=$2+$3; printf wage}’ file 找到匹配行后为变量wage赋值并打印该变量。 12、 awk ‘/tom/ {count++;} END {print “tom was found “count” times”}’ file END表示在所有输入行处理完后进行处理。 13、 awk ‘gsub(/\$/,”");gsub(/,/,”"); cost+=$4; END {print “The total is $” cost>“filename”}’ file gsub函数用空串替换$和,再将结果输出到filename中。 1 2 3 $1,200.00 1 2 3 $2,300.00 1 2 3 $4,000.00 awk ‘{gsub(/\$/,”");gsub(/,/,”"); if ($4>1000&&$4<2000) c1+=$4; else if ($4>2000&&$4<3000) c2+=$4; else if ($4>3000&&$4<4000) c3+=$4; else c4+=$4; } END {printf "c1=[%d];c2=[%d];c3=[%d];c4=[%d]\n",c1,c2,c3,c4}"' file 通过if和else if完成条件语句 awk '{gsub(/\$/,"");gsub(/,/,""); if ($4>3000&&$4<4000) exit; else c4+=$4; } END {printf "c1=[%d];c2=[%d];c3=[%d];c4=[%d]\n",c1,c2,c3,c4}"' file 通过exit在某条件时退出,但是仍执行END操作。 awk '{gsub(/\$/,"");gsub(/,/,""); if ($4>3000) next; else c4+=$4; } END {printf “c4=[%d]\n”,c4}”‘ file 通过next在某条件时跳过该行,对下一行执行操作。 14、 awk ‘{ print FILENAME,$0 }’ file1 file2 file3>fileall 把file1、file2、file3的文件内容全部写到fileall中,格式为打印文件并前置文件名。 15、 awk ‘ $1!=previous { close(previous); previous=$1 } {print substr($0,index($0,” “) +1)>$1}’ fileall 把合并后的文件重新分拆为3个文件。并与原文件一致。 16、 awk ‘BEGIN {“date”|getline d; print d}’ 通过管道把date的执行结果送给getline,并赋给变量d,然后打印。 17、 awk ‘BEGIN {system(“echo \”Input your name:\\c\”"); getline d;print “\nYour name is”,d,”\b!\n”}’ 通过getline命令交互输入name,并显示出来。 awk ‘BEGIN {FS=“:”; while(getline< "/etc/passwd" >0) { if($1~”050[0-9]_”) print $1}}’ 打印/etc/passwd文件中用户名包含050x_的用户名。 18、 awk '{ i=1;while(i19、 在awk中调用系统变量必须用单引号,如果是双引号,则表示字符串 Flag=abcd awk ‘{print ‘$Flag’}’ 结果为abcd awk ‘{print “$Flag”}’ 结果为$Flag
相关阅读:
|