1.功能
用于去除有序文件中的重复行并将结果输出到标准输出。uniq经常和sort合用,为了使uniq起作用,所有的重复行必须是相邻的。
2.格式
uniq [选项] [file]
选项说明:
- -c, --count //在每行前加上表示相应行目出现次数的前缀编号
- -d, --repeated //只输出重复的行
- -D, --all-repeated //只输出重复的行,不过有几行输出几行
- -f, --skip-fields=N //-f 忽略的段数,-f 1 忽略第一段
- -i, --ignore-case //不区分大小写
- -s, --skip-chars=N //根-f有点像,不过-s是忽略,后面多少个字符 -s 5就忽略后面5个字符
- -u, --unique //去除重复的后,全部显示出来
- -z, --zero-terminated end lines with 0 byte, not newline
- -w, --check-chars=N //对每行第N 个字符以后的内容不作对照
- --help //显示此帮助信息并退出
- --version //显示版本信息并退出
3.常用示例
(1)对无序文件去重无效。
testfile的内容如下:
[root@qiangdalao shells]# cat testfile
hello
world
friend
hello
world
hello
直接删除未经排序的文件,将会发现没有任何行被删除(uniq只能删除相邻的重复行):
[root@qiangdalao shells]# uniq testfile
hello
world
friend
hello
world
hello
(2)uniq结合sort命令,对排序文件去重。
[root@qiangdalao shells]# cat testfile |sort |uniq
friend
hello
world
(3)排序之后删除了重复行,同时在行首位置输出该行重复的次数。
[root@qiangdalao shells]# sort testfile |uniq -c
1 friend
3 hello
2 world
(4)仅显示存在重复的行,并在行首显示该行重复的次数:
[root@qiangdalao shells]# sort testfile |uniq -dc
3 hello
2 world
(5)仅显示不重复的行。
[root@qiangdalao shells]# sort testfile |uniq -u
friend
(6)仅显示重复的行,且显示重复行的所有行。
[root@qiangdalao shells]# sort testfile |uniq -D
hello
hello
hello
world
world
(7)uniq默认是比较相邻行的所有内容来判断是否重复,我们可以通过选项-w
或--check-chars=N
指定比较前N个字符。比如我们有如下内容的文件test.txt:
[root@qiangdalao shells]# cat test.txt
apple
application
api
打印前三个字符相同的行(相当于文件我只比较前三个字符了):
[root@qiangdalao shells]# uniq -w3 -D test.txt
apple
application
参考博客:https://blog.youkuaiyun.com/technologyleader/article/details/81941410