参考链接sort https://www.runoob.com/linux/linux-comm-sort.html
参考链接uniq https://www.runoob.com/linux/linux-comm-uniq.html
一、sort命令
sort testfile
sort 命令将以默认的方式将文本文件的第一列以 ASCII 码的次序排列,并将结果输出到标准输出。
使用 cat 命令显示 testfile 文件可知其原有的排序如下:
$ cat testfile # testfile文件原有排序
test 30
Hello 95
Linux 85
使用 sort 命令重排后的结果如下:
$ sort testfile # 重排结果
Hello 95
Linux 85
test 30
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 命令是不起作用的
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
- 检查文件并删除文件中重复出现的行,并在行首显示该行重复出现的次数。使用如下命令:
uniq -c testfile
结果输出如下:
$ uniq -c testfile #删除重复行后的内容
3 test 30 #前面的数字的意义为该行共出现了3次
4 Hello 95 #前面的数字的意义为该行共出现了4次
2 Linux 85 #前面的数字的意义为该行共出现了2次
- 当文本中的文件未排序时,
$ 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