linux uniq命令详解

转自:http://blog.csdn.net/zzxian/article/details/7200046

uniq [选项] 文件

说明:这个命令读取输入文件,并比较相邻的行。在正常情况下,第二个及以后更多个重复行将被删去,行比较是根据所用字符集的排序序列进行的。该命令加工后的结果写到输出文件中。输入文件和输出文件必须不同。如果输入文件用“- ”表示,则从标准输入读取。

该命令各选项含义如下:、

– c 显示输出中,在每行行首加上本行在文件中出现的次数。它可取代- u和- d选项。

– d 只显示重复行。

– u 只显示文件中不重复的各行。

– n 前n个字段与每个字段前的空白一起被忽略。一个字段是一个非空格、非制表符的字符串,彼此由制表符和空格隔开(字段从0开始编号)。

+n 前n个字符被忽略,之前的字符被跳过(字符从0开始编号)。

– f n 与- n相同,这里n是字段数。

– s n 与+n相同,这里n是字符数。

接下来通过实践实例说明:

===========================================

[root@stu100 ~]# cat test
boy took bat home
boy took bat home
girl took bat home
boy took bat home
boy took bat home
dog brought hat home
dog brought hat home
dog brought hat home

看test文件的内容

============================================

[root@stu100 ~]# uniq test
boy took bat home
girl took bat home
boy took bat home
dog brought hat home

uniq命令不加任何参数,仅显示连续重复的行一次

============================================

[root@stu100 ~]# uniq -c test
2 boy took bat home
1 girl took bat home
2 boy took bat home
3 dog brought hat home
1

-c 参数显示文件中每行连续出现的次数。

============================================

[root@stu100 ~]# cat test |sort | uniq -c
1
4 boy took bat home
3 dog brought hat home
1 girl took bat home

排序后再显示

============================================

[root@stu100 ~]# uniq -d test
boy took bat home
boy took bat home
dog brought hat home

-d选项仅显示文件中连续重复出现的行。

============================================

[root@stu100 ~]# uniq -u test
girl took bat home

-u选项显示文件中没有连续出现的行。

============================================

[root@stu100 ~]# uniq -f 2 -s 2 test
boy took bat home

忽略每行的前2个字段,忽略第二 个空白字符和第三个字段的首字符,结果at home

============================================

[root@stu100 ~]# uniq -f 1 test
boy took bat home
dog brought hat home

忽 略每行的第一个字段,这样boy ,girl开头的行看起来是连续重复的行。

============================================

[root@stu100 ~]# uniq -D test
boy took bat home
boy took bat home
boy took bat home
boy took bat home
dog brought hat home
dog brought hat home
dog brought hat home

显示所有重复的行,每个重复的行都显示

相关推荐