Linux uniq 命令

Linux 命令大全 Linux 命令大全

Linux uniq 命令用於檢查及刪除文本檔中重複出現的行列,一般與 sort 命令結合使用。

uniq 可檢查文本檔中重複出現的行列。

語法

uniq [-cdu][-f<欄位>][-s<字元位置>][-w<字元位置>][--help][--version][輸入檔][輸出檔]

參數

  • -c或--count 在每列旁邊顯示該行重複出現的次數。
  • -d或--repeated 僅顯示重複出現的行列。
  • -f<欄位>或--skip-fields=<欄位> 忽略比較指定的欄位。
  • -s<字元位置>或--skip-chars=<字元位置> 忽略比較指定的字元。
  • -u或--unique 僅顯示出一次的行列。
  • -w<字元位置>或--check-chars=<字元位置> 指定要比較的字元。
  • --help 顯示幫助。
  • --version 顯示版本資訊。
  • [輸入檔] 指定已排序好的文本檔。如果不指定此項,則從標準讀取數據;
  • [輸出檔] 指定輸出的檔。如果不指定此選項,則將內容顯示到標準輸出設備(顯示終端)。

實例

檔testfile中第 2、3、5、6、7、9行為相同的行,使用 uniq 命令刪除重複的行,可使用以下命令:

uniq testfile

testfile中的原有內容為:

$ cat testfile      #原有內容
test 30
test 30
test 30
Hello 95
Hello 95
Hello 95
Hello 95
Linux 85
Linux 85

使用uniq 命令刪除重複的行後,有如下輸出結果:

$ uniq testfile     #刪除重複行後的內容

test 30
Hello 95
Linux 85

檢查檔並刪除檔中重複出現的行,並在行首顯示該行重複出現的次數。使用如下命令:

uniq -c testfile

結果輸出如下:

$ uniq -c testfile      #刪除重複行後的內容

3 test 30             #前面的數字的意義為該行共出現了3次

4 Hello 95            #前面的數字的意義為該行共出現了4次

2 Linux 85            #前面的數字的意義為該行共出現了2次

當重複的行並不相鄰時,uniq 命令是不起作用的,即若檔內容為以下時,uniq 命令不起作用:
$ cat testfile1      # 原有內容
test 30
Hello 95
Linux 85
test 30
Hello 95
Linux 85
test 30
Hello 95
Linux 85 

這時我們就可以使用 sort:

$ sort  testfile1 | uniq
Hello 95
Linux 85
test 30

統計各行在檔中出現的次數:

$ sort testfile1 | uniq -c
   3 Hello 95
   3 Linux 85
   3 test 30

在檔中找出重複的行:

$ sort testfile1 | uniq -d
Hello 95
Linux 85
test 30

Linux 命令大全 Linux 命令大全