shell脚本--awk数组实现去除重复行

去除重复行的方法有很多,这里介绍三种。

测试文本:

[root@172-0-10-222 myscripts]# cat testfile
andy 123456
hanna 123456
hello world
welcome fuck
andy 123456
hello world
andy andy

这其中,有andy 123456和hello world是重复的。

(1)使用sort、uniq命令去除重复行

[root@172-0-10-222 myscripts]# cat testfile | sort | uniq
andy 123456
andy andy
hanna 123456
hello world
welcome fuck

这里是先将每一行进行默认规则排序,然后把重复的行去掉。

(2)使用awk数组去除重复行

[root@172-0-10-222 myscripts]# cat testfile | awk '!arr[$0]++{print $0}'
andy 123456
hanna 123456
hello world
welcome fuck
andy andy

也可以简写成 cat testfile | awk '!arr[$0]++'

分析:将每一行数据作为数组的下标,某下标x第一次出现的时候arr[x]为0,第二次,第三次,。。。,第n次出现的时候arr[x]不为0。这里,!arr[$0]++是选择第一次出现的行进行打印输出。

(3)使用awk数组去除重复行详细写法

[root@172-0-10-222 myscripts]# cat testfile | awk '{arr[$0]=1}END{for(i in arr){print i}}'
welcome fuck
hanna 123456
andy 123456
hello world
andy andy

分析:以每一行作为数组下标给数组赋值,重复行下标就会替换掉前面的下标。然后输出留下来的下标即可。

 

案例:去除重复号码行

号码文件

[root@172-0-10-222 myscripts]# cat testfile
andy 15871731153
hanna 15387876543
hello 15578765389
welcome 15871731153
andy 13987273647
hello 15871731153
andy 15871731153

去除文件中号码重复的行

[root@172-0-10-222 myscripts]# cat testfile | awk '!arr[$2]++'
andy 15871731153
hanna 15387876543
hello 15578765389
andy 13987273647

 

发布了71 篇原创文章 · 获赞 5 · 访问量 6454
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章