天天看點

awk

#1 應用

  awk -F:   '{print$0 "-->" $1 "-->" $2 }' /etc/passwd

#2 多個比對

  awk'/yeqing|mysql|nginx/' /etc/passwd     

#3 正則比對

  awk '/^yeqing|mysql$/' /etc/passwd 

#4 将小寫轉換成大寫

  cat yeqing.txt |tr 'a-z' 'A-Z' > p.txt 

 或者

 awk '/yeqing/'/etc/passwd |tr "a-z" "A-Z" >tmp.txt

#5 取出第二行

  ifconfig eth0 |awk -F':' 'NR==2 {print $2}'  

 ifconfig eth0 |awk -F: 'NR==2{print $2}' |awk-F' ' '{print $1}'

#6 取出第二行用“空格”或者“:”去分割

  ifconfig eth0 |awk -F '[ :]+' 'NR==2 {print $4}'

#7 統計

  awk '{count++}END{print "ct:",count}' /etc/passwd

  awk '{i++}END{print i}' /etc/passwd

 cat /etc/passwd |wc -l

#8 統計某個檔案夾下的檔案占用的位元組數:

  ls -l |awk -F ' ' 'BEGIN {size=0;} {size=size+$5;} END{print "size:",size}'

  以M為機關顯示

  ls -l |awk'BEGIN {size=0;} {size=size+$5;} END{print "[end]size is ",size/1024/1024,"M"}'

#9 分析access.log獲得通路前10位的ip位址

    awk '{print $1}'access.log |sort|uniq -c|sort -nr|head -10

    或者

    awk '{print $1}'/usr/local/sina_mobile/nginx/logs/access.log |sort|uniq -c|sort -nr|head -10

    tail/usr/local/sina_mobile/nginx/logs/access.log |awk -F ' ' '{print $1}'|sort|uniq -c |sort –nr

#10 分開|過濾|顯示

tail /etc/passwd|awk -F ':' '{if(substr($1,0,2)=="ye"){ print $0}}'

#11  4舍5入

cat ye.txt |awk-F. '{if(substr($2,1,1)>=5)$1+=1 ; print $1}'

或者

cat ye.txt |awk'{print int($1+0.5)}'

#12 分析日志

tail/usr/local/sina_mobile/nginx/logs/access.log |awk -F '- -' '/[GET]/{print $1}'|sort -nru 

awk -F "--" '{if($0 ~ /index.html/) print $1}' test

#13 生産案例:

[root@home-web1scripts]# cat name

張三 10億

李四 200萬

王五 100千

[root@home-web1scripts]# cat info

上海 張三

北京 李四

南京 王五

[root@home-web1scripts]# awk 'FNR==NR{arr[$1]=$0;next}{print arr[$2],$1}' name info

張三 10億 上海

李四 200萬 北京

王五 100千 南京

本文轉自cloves 51CTO部落格,原文連結:http://blog.51cto.com/yeqing/1598296

上一篇: sed
下一篇: grep使用

繼續閱讀