,a,"");for(i=1;i<=len;i++) print "a["i"] = " a[i];print "length = " len}' a[1] = a a[2] = b a[3] = c a[4] = d " />

Shell数组和awk数组(2)

电脑杂谈  发布时间:2020-05-06 19:38:21  来源:网络整理

[root@localhost~]# echo 'abcd' |awk '{len=split($0,a,"");for(i=1;i<=len;i++) print "a["i"] = " a[i];print "length = " len}'
a[1] = a
a[2] = b
a[3] = c
a[4] = d
length = 4

在一月份查找相同的名称和总和

[root@localhost~]# cat file 
Tom     2012-12-11      car     5       3000
John    2013-01-13      bike    4       1000
vivi    2013-01-18      car     4       2800
Tom     2013-01-20      car     3       2500
John    2013-01-28      bike    6       3500
[root@localhost~]# awk '{split($2,a,"-");if(a[2]==01){b[$1]+=$5}}END{for(i in b)print i,b[i]}' file 
vivi 2800
Tom 2500
John 4500

9. 找到平均值

[root@localhost~]# cat file 
/circlelistbytjid,耗时:25ms
/circlelistbytjid,耗时:24ms
/circlelistbytjid,耗时:21ms
/circlelistbytjid,耗时:13ms
/circlelistbytjid,耗时:25ms
/circlelistbytjid,耗时:13ms
/circlelistbytjid,耗时:23ms
/circlelistbytjid,耗时:24ms
[root@localhost~]# awk -F: '{a+=+$2}END{print a/NR}' file
21

[root@localhost~]# cat file
alex 20
tom 30
alex 10
tom 20
[root@localhost~]# awk '{a[$1]+=$2;b[$1]++}END{for(i in a) print i,a[i]/b[i]}' file
alex 15
tom 25

awk数组_awk数组初始化_awk数组下标

10. 找到最大值

获取数字字段的最大值

[root@localhost~]# cat file 
a b 1 
c d 2 
e f 3 
g h 3 
i j 2
[root@localhost~]# awk 'BEGIN{max=0}{if($3>max)max=$3}END{print max}' file
3

打印第三个字段的最大行

[root@localhost~]# awk 'BEGIN{max=0}{a[$0]=$3;if($3>max)max=$3}END{for(v in a)if(a[v]==max)print v}' file
e f 3 
g h 3

11. 结合file1和file2删除重复项

[root@localhost~]#cat file1
aaa
bbb
ccc
ddd
[root@localhost~]#cat file2
aaa
eee
ddd
fff
[root@localhost~]# awk 'NR==FNR{a[$0]=1;print}   #读取file1,建立数组a,下标为$0,并赋值为1,然后打印
NR>FNR{                   #读取file2
if(!(a[$0])) {print }      #如果file2 的$0不存在于数组a中,即不存在于file1,则打印。
}' file1 file2
aaa
bbb
ccc
ddd
eee
fff

存在于文件1中,但不存在于文件2中:

[root@localhost~]# awk 'NR==FNR{a[$0]=1}           #读取file2,建立数组a,下标为$0,并赋值为1
NR>FNR{                   #读取file1
if(!(a[$0])) {print }      #如果file1 的$0不存在于数组a中,即不存在于file2,则打印。
}' file2 file1
bbb
ccc

参考文章:


本文来自电脑杂谈,转载请注明本文网址:
https://www.pc-fly.com/a/jisuanjixue/article-200910-2.html

相关阅读
    发表评论  请自觉遵守互联网相关的政策法规,严禁发布、暴力、反动的言论

    热点图片
    拼命载入中...