实例解说Linux命令行uniq

2011-07-11 13:20 zhang liangkun.net字号:T|T

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


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 bathome

boy took bathome

girl took bathome

boy took bathome

boy took bathome

dog brought hathome

dog brought hathome

dog brought hathome

看test文件的内容

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

[root@stu100 ~]#uniq test

boy took bathome

girl took bathome

boy took bathome

dog brought hathome

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

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

[root@stu100 ~]# uniq -c test

2 boy took bathome

1 girl took bathome

2 boy took bathome

3 dog broughthat home

1

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

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

[root@stu100 ~]#cat test |sort | uniq -c

1

4 boy took bathome

3 dog broughthat home

1 girl took bathome

排序后再显示

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

[root@stu100 ~]#uniq -d test

boy took bathome

boy took bathome

dog brought hathome

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

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

[root@stu100 ~]#uniq -u test

girl took bathome

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

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

[root@stu100 ~]#uniq -f 2 -s 2 test

boy took bathome

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

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

[root@stu100 ~]#uniq -f 1 test

boy took bathome

dog brought hathome

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

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

[root@stu100 ~]#uniq -D test

boy took bathome

boy took bathome

boy took bathome

boy took bathome

dog brought hathome

dog brought hathome

dog brought hathome

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