awk用法汇总

1.格式化打印

awk '{printf "%-8s %-8s %-8s %-18s\n",NR, $1,$2,$12}' top.txt

  

2.对一列数据求和

awk 'BEGIN {sum=0} {printf "%-8s %-8s %-18s\n", $1, $9, $11; sum+=$9} END {print "cpu_sum="sum}' test.txt

  

3.去除表头,打印cpu大于0的行

awk 'NR>1 && $9>0 {printf "%-8s %-8s %-8s\n", $1, $9, $11}' test.txt

  

4.匹配列关键字

awk 'NR==1 || $3~/rt/ {printf "%-8s %-8s %-8s\n", $1, $3, $9}' test.txt

  

5.获取数组长度

awk 'BEGIN{info="it is a test";lens=split(info, taa, " "); print length(taa), lens}'

  

6.无序输出数组

awk 'BEGIN {info="this is a test"; split(info, taa, " "); for(k in taa) {print k, taa[k];}}'

  

7.有序输出数组

awk 'BEGIN {info="this is a test"; tlen=split(info, taa, " "); for(k=1;k<=tlen;k++){print k, taa[k]}}'

  

8.判断是否存在key

awk 'BEGIN{tB["a"]="a1";tB["b"]="b1";if( "c" in tB){print "ok";};for(k in tB){print k,tB[k];}}'

  

9.删除key

awk 'BEGIN{tB["a"]="a1";tB["b"]="b1";delete tB["a"];for(k in tB){print k,tB[k];}}'                     

  

posted @ 2022-03-14 18:14  karry2karry  阅读(131)  评论(0)    收藏  举报