介绍:

重复行通常不会造成问题,但是有时候它们的确会引起问题。此时,不必花上一个下午的时间来为它们编制过滤器,uniq 命令便是唾手可得的好工具

进行排序之后,您会发现有些行是重复的。有时候该重复信息是不需要的,可以将它除去以节省磁盘空间。不必对文本行进行排序,但是您应当记住 uniq 在读取行时会对它们进行比较并将只除去两个或更多的连续行。行比较是根据所用字符集的排序序列进行的。该命令加工后的结果写到输出文件中。输入文件和输出文件必须不同。如果输入文件用“- ”表示,则从标准输入读取。

用法;

NAME
       uniq - report or omit repeated lines
SYNOPSIS
       uniq [OPTION]... [INPUT [OUTPUT]]
DESCRIPTION
       Discard all but one of successive identical lines from INPUT (or standard input), writing to OUTPUT (or standard output).
       Mandatory arguments to long options are mandatory for short options too.
       -c, --count
              prefix lines by the number of occurrences
       -d, --repeated
              only print duplicate lines
       -D, --all-repeated[=delimit-method] print all duplicate lines
              delimit-method={none(default),prepend,separate} Delimiting is done with blank lines.
       -f, --skip-fields=N
              avoid comparing the first N fields
       -i, --ignore-case
              ignore differences in case when comparing
       -s, --skip-chars=N
              avoid comparing the first N characters
       -u, --unique
              only print unique lines
       -w, --check-chars=N
              compare no more than N characters in lines
       --help display this help and exit

解释:

– c 显示输出中,在每行行首加上本行在文件中出现的次数。它可取代- u和- d选项。
– d 只显示重复行。
– u 只显示文件中不重复的各行。
– n 前n个字段与每个字段前的空白一起被忽略。一个字段是一个非空格、非制表符的字符串,彼此由制表符和空格隔开(字段从0开始编号)。
+n 前n个字符被忽略,之前的字符被跳过(字符从0开始编号)。
– f n 与- n相同,这里n是字段数。
– s n 与+n相同,这里n是字符数。

实例:

文件:

[root@uyhd000225 testDir]# more fruits
banana
orange
Persimmon
apple
%%banana
apple
ORANGE

去除不连续的重复行(没有成功):

[root@uyhd000225 testDir]# uniq fruits
banana
orange
Persimmon
apple
%%banana
apple
ORANGE

去除连续的重复行:

[root@uyhd000225 testDir]# more fruits |sort|uniq
apple
banana
%%banana
orange
ORANGE
Persimmon
[root@uyhd000225 testDir]# sort fruits |uniq
apple
banana
%%banana
orange
ORANGE
Persimmon

去除后保存为另外的文件:

[root@uyhd000225 testDir]# sort fruits |uniq fruit2
uniq: fruit2: 没有那个文件或目录
[root@uyhd000225 testDir]# sort fruits
apple
apple
banana
%%banana
orange
ORANGE
Persimmon
[root@uyhd000225 testDir]# sort fruits>fruits2
[root@uyhd000225 testDir]# uniq fruits2 fruits3
[root@uyhd000225 testDir]# more fruits3
apple
banana
%%banana
orange
ORANGE
Persimmon
[root@uyhd000225 testDir]# more fruits2
apple
apple
banana
%%banana
orange
ORANGE
Persimmon
[root@uyhd000225 testDir]# sort fruits |uniq - fruit4
[root@uyhd000225 testDir]# more fruit4
apple
banana
%%banana
orange
ORANGE
Persimmon