Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Linux uniq Command

Linux uniq Command

Linux Command Reference Linux Command Reference

The Linux uniq command is used to detect and remove repeated lines in a text file, and is generally used in combination with the sort command.

uniq can detect repeated lines in a text file.

Syntax



uniq [-cdu][-f<栏位>][-s<字符位置>][-w<字符位置>][--help][--version][输入文件][输出文件]

Parameters:

Example

Lines 2, 3, 5, 6, 7, and 9 in the file testfile are identical; to remove the duplicate lines with the uniq command, use the following command:



uniq testfile 

The original content of testfile is:



$ cat testfile      #原有内容  

test 30  

test 30  

test 30  

Hello 95  

Hello 95  

Hello 95  

Hello 95  

Linux 85  

Linux 85 

After using the uniq command to remove duplicate lines, the output is as follows:



$ uniq testfile     #删除重复行后的内容  

test 30  

Hello 95  

Linux 85 

Check a file, remove repeated lines, and display at the beginning of each line the number of times it occurs. Use the following command:



uniq -c testfile 

The resulting output is as follows:



$ uniq -c testfile      #删除重复行后的内容  

3 test 30             #前面的数字的意义为该行共出现了3次  

4 Hello 95            #前面的数字的意义为该行共出现了4次  

2 Linux 85            #前面的数字的意义为该行共出现了2次 

When duplicate lines are not adjacent, the uniq command has no effect; that is, if the file content is as follows, uniq will not work:

$ cat testfile1      # 原有内容 

test 30  

Hello 95  

Linux 85 

test 30  

Hello 95  

Linux 85 

test 30  

Hello 95  

Linux 85 

In this case we can use sort:



$ sort  testfile1 | uniq

Hello 95  

Linux 85 

test 30

Count the number of times each line appears in the file:

$ sort testfile1 | uniq -c

   3 Hello 95  

   3 Linux 85 

   3 test 30

Find the repeated lines in the file:

$ sort testfile1 | uniq -d

Hello 95  

Linux 85 

test 30  

Linux Command Reference Linux Command Reference