[Shell] awk学习(1)-pattern{action}

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/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/24237320/viewspace-2077417/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值