[Shell] awk學習(1)-pattern{action}

tolilong發表於2016-04-08
awk pattern{action}
其中如果pattern為true,則執行action

樣例data file
[/tmp/test]# cat ff1
aardvark 555-5553 1200/300 B
alpo-net 555-3412 2400/1200/300 A
barfly 555-7685 1200/300 A
bites 555-1675 2400/1200/300 A
camelot 555-0542 300 C
core 555-2912 1200/300 C
fooey 555-1234 2400/1200/300 B
foot 555-6699 1200/300 B
macfoo 555-6480 1200/300 A
sdace 555-3430 2400/1200/300 A
sabafoo 555-2127 1200/300 C


[/tmp/test]# cat ff2
Jan 13 25 15 115
Feb 15 32 24 226
Mar 15 24 34 228
Apr 31 52 63 420
May 16 34 29 208
Jun 31 42 75 492
Jul 24 34 67 436
Aug 15 34 47 316
Sep 13 55 37 277
Oct 29 54 68 525
Nov 20 87 82 577
Dec 17 35 61 401


Jan 21 36 64 620
Feb 26 58 80 652
Mar 24 75 70 495
Apr 21 70 74 514


1.統計大小(bytes&k)
[/tmp/test]# ll | awk '{x+=$5}END{print "total bytes is "x}'
total bytes is 2432
[/tmp/test]# ll | awk '{x+=$5}END{print "total k-bytes is "x/1024}'
total k-bytes is 2.375

2.去除空白行
[/tmp/test]# awk 'NF>0' ff2
Jan 13 25 15 115
Feb 15 32 24 226
Mar 15 24 34 228
Apr 31 52 63 420
May 16 34 29 208
Jun 31 42 75 492
Jul 24 34 67 436
Aug 15 34 47 316
Sep 13 55 37 277
Oct 29 54 68 525
Nov 20 87 82 577
Dec 17 35 61 401
Jan 21 36 64 620
Feb 26 58 80 652
Mar 24 75 70 495
Apr 21 70 74 514

3.列印長度最長的行
[/tmp/test]# awk '{if(length($0)>max){max=length($0);str=$0}}END{print max,"===",str}' ff1
33 === alpo-net 555-3412 2400/1200/300 A
列印長度大於30的行
awk '{length($0)>30}' ff1

4.隨機列印8個整數,要按回車才有反應,奇怪了。
[/tmp/test]# awk '{for(i=1;i<=8;i++){print int(100*rand())}}'    

51
17
30
53
94
17
70
22

5.計算多少行
[/tmp/test]# cat /etc/passwd | wc -l
25
[/tmp/test]# cat /etc/passwd | awk 'END{print NR}'
25

6.pattern中有多個條件
[/tmp/test]# awk '$2>30 && $5>450 {print $0}' ff2
Jun 31 42 75 492

6.列印奇數或者偶數行
[/tmp/test]# awk 'NR%2==1' ff1
[/tmp/test]# awk 'NR%2==0' ff1

7.有多個pattern的情況
[/tmp/test]# awk '/foo/{print $0} /21/{print $0}' ff1 ff2                 第一個pattern會對ff1進行匹配,第二個pattern會對ff2進行匹配
[/tmp/test]# awk '/foo/{print $0} /C/{print $0}' ff1                      第一個pattern會對ff1進行匹配,第二個pattern也是對ff1進行匹配

8.選擇line,統計大小
[/tmp/test]# ll | awk '$6=="Mar"{x+=$5}END{print x}'
1046

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/24237320/viewspace-2077417/,如需轉載,請註明出處,否則將追究法律責任。

相關文章