linux shell 数组 去重复,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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值