shell中的sort和uniq命令

参考链接sort https://www.runoob.com/linux/linux-comm-sort.html
参考链接uniq https://www.runoob.com/linux/linux-comm-uniq.html

一、sort命令

  1. sort testfile
    sort 命令将以默认的方式将文本文件的第一列以 ASCII 码的次序排列,并将结果输出到标准输出。
使用 cat 命令显示 testfile 文件可知其原有的排序如下:

$ cat testfile      # testfile文件原有排序  
test 30  
Hello 95  
Linux 85 
使用 sort 命令重排后的结果如下:

$ sort testfile # 重排结果  
Hello 95  
Linux 85  
test 30 
  1. sort -u testfile 意味着是唯一的(unique),输出的结果是去完重了的。
$ cat testfile      # testfile文件原有排序  
test 30
Hello 95
Linux 85
test 30
Hello 95
Linux 85
hhh 85
kkk 1
Linux 85

使用 sort -u 命令重排后的结果如下:

$ sort -u testfile # 重排结果  
Hello 95
hhh 85
kkk 1
Linux 85
test 30

二、uniq命令

uniq的操作对象是排序后的文本,当重复的行并不相邻时,uniq 命令是不起作用的

  1. uniq testfile
    testfile中的原有内容为:
$ cat testfile      #原有内容  
test 30  
test 30  
test 30  
Hello 95  
Hello 95  
Hello 95  
Hello 95  
Linux 85  
Linux 85 

使用uniq 命令删除重复的行后,有如下输出结果:

$ uniq testfile     #删除重复行后的内容  
test 30  
Hello 95  
Linux 85 
  1. 检查文件并删除文件中重复出现的行,并在行首显示该行重复出现的次数。使用如下命令:
uniq -c testfile 

结果输出如下:

$ uniq -c testfile      #删除重复行后的内容  
3 test 30             #前面的数字的意义为该行共出现了3次  
4 Hello 95            #前面的数字的意义为该行共出现了4次  
2 Linux 85            #前面的数字的意义为该行共出现了2次 
  1. 当文本中的文件未排序时,
$ cat testfile1      # 原有内容 
test 30  
Hello 95  
Linux 85 
test 30  
Hello 95  
Linux 85 
test 30  
Hello 95  
Linux 85 

先对文本进行排序,然后执行uniq -c统计每行文本出现的次数

sort testfile1 | uniq -c
 3 Hello 95  
 3 Linux 85 
 3 test 30

找出重复的行

$ sort testfile1 | uniq -d
Hello 95  
Linux 85 
test 30  

  • 6
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值