uniq是对文本文件进行行去去重的工具。
- 以行为单位,进行行与行之间的字符串比较并进行去重
- 只能对有序的文本行进行有效去重,所以常与sort命令结合使用
参数 | 解释 |
---|---|
-c | 统计行出现的次数 |
-d | 只显示重复的行并且去重 |
-u | 只显示唯一的行 |
-i | 忽略字母大小写 |
-f | 忽略前N个字段(字段间用空白字符分隔) |
root@shark:/home/sll/vm_share# cat hello.sh
hello this is linux
be better
be better
i am lhj
hello this is linux
i am lhj
i am lhj
be better
i am lhj
have a nice day
have a nice day
hello this is linux
hello this is linux
have a nice day
zzzzzzzzzzzzzz
dddddddd
gggggggggggggggggggg
root@shark:/home/sll/vm_share#
【1】单独使用uniq命令
root@shark:/home/sll/vm_share# uniq hello.sh
hello this is linux
be better
i am lhj
hello this is linux
i am lhj
be better
i am lhj
have a nice day
hello this is linux
have a nice day
zzzzzzzzzzzzzz
dddddddd
gggggggggggggggggggg
root@shark:/home/sll/vm_share#
可以看出单独使用uniq命令时只对相邻重复行进行去重,无法进行有效去重
【2】与sort结合使用
root@shark:/home/sll/vm_share# sort hello.sh | uniq
be better
dddddddd
gggggggggggggggggggg
have a nice day
hello this is linux
i am lhj
zzzzzzzzzzzzzz
root@shark:/home/sll/vm_share#
先排序使重复的行相邻,然后使用uniq可以有效去重
【3】uniq支持管道符
root@shark:/home/sll/vm_share# cat hello.sh | sort | uniq
be better
dddddddd
gggggggggggggggggggg
have a nice day
hello this is linux
i am lhj
zzzzzzzzzzzzzz
root@shark:/home/sll/vm_share#
上次写sort那篇文章时说到sort支持管道符,同样uniq也一样支持管道符
2.统计出现的次数,使用-c参数
使用-c,–count可以统计重复行出现的次数
root@shark:/home/sll/vm_share# cat hello.sh | sort | uniq -c
3 be better
1 dddddddd
1 gggggggggggggggggggg
3 have a nice day
4 hello this is linux
4 i am lhj
1 zzzzzzzzzzzzzz
root@shark:/home/sll/vm_share#
3.只显示重复的行并且去重,使用-d参数
使用-d,–repeated只显示重复的行并且重复的行只显示一次
root@shark:/home/sll/vm_share# cat hello.sh | sort | uniq -dc
3 be better
3 have a nice day
4 hello this is linux
4 i am lhj
root@shark:/home/sll/vm_share#
可以看到末尾的三行不重复的行没有显示,将重复的行进行去重后显示
3.只显示唯一的行,使用-u参数
root@shark:/home/sll/vm_share# cat hello.sh | sort | uniq -u
dddddddd
gggggggggggggggggggg
zzzzzzzzzzzzzz
root@shark:/home/sll/vm_share#
只有末尾三行是唯一的,所以只显示末尾的三行文本
4.忽略字母大小写,使用-i参数
root@shark:/home/sll/vm_share# cat test.txt
I am LHJ
i am lhj
HELLO this Is Zhang
hello this is zhang
root@shark:/home/sll/vm_share# cat test.txt | sort | uniq -i
hello this is zhang
i am lhj
root@shark:/home/sll/vm_share#
5.忽略前N个字段进行去重,使用-f参数
root@shark:/home/sll/vm_share# cat test.txt
1 I am LHJ
2 i am lhj
3 HELLO this Is Zhang
4 hello this is zhang
root@shark:/home/sll/vm_share# cat test.txt | sort | uniq -i -f 1
1 I am LHJ
3 HELLO this Is Zhang
root@shark:/home/sll/vm_share#
test.txt文件中每一行之前有行号,无法使用sort和uniq进行去重,可以使用-f参数忽略每一行的第一个字段,这样就可以忽略每一行之前的行号,对每一行之后的内容进行去重处理。
注意:字段之间必须是空白字符(空格或者tap键均属于空白字符)分隔,使用其他字符无法识别
对于这种情况也可以使用awk命令工具进行处理去除第一列的行号,然后通过管道符丢给sort和uniq命令处理,后续会继续更新awk等重要的文本处理工具。