Linux uniq Command
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:
- -c or --count Display the number of times each line appears next to it.
- -d or --repeated Display only repeated lines.
- -f
or --skip-fields= Ignore the specified fields when comparing. - -s
or --skip-chars= Ignore the specified characters when comparing. - -u or --unique Display only lines that appear once.
- -w
or --check-chars= Specify the characters to compare. - --help Display help.
- --version Display version information.
- [input file] Specify the sorted text file. If this is not specified, data is read from standard input;
- [output file] Specify the output file. If this option is not specified, the content is displayed to the standard output device (the display terminal).
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