uniq#

uniq 是包含在 GNU Coreutils 內的文字去重工具。

uniq 是 Linux 系統中用於報告或過濾檔案中「連續重複行」的指令。它通常與 sort 指令搭配使用,因為 uniq 只能偵測相鄰的重複行。透過 uniq,你可以快速找出重複資料、統計出現次數或僅顯示唯一的內容。

Install#

$ sudo apt install coreutils

Setting in up#


Operate#

uniq [options] [file]

先排序後去重(最常見用法)#

sort file.txt | uniq

統計各行出現次數#

sort file.txt | uniq -c

僅顯示有重複過的行#

sort file.txt | uniq -d

參數範例指令說明
-cuniq -c file計數。在每一行前面顯示該行重複出現的次數。
-duniq -d file顯示重複。僅輸出檔案中重複出現過的內容。
-uuniq -u file顯示唯一。僅輸出檔案中「從未重複」過的內容。
-iuniq -i file忽略大小寫。比較時不區分英文字母大小寫。
-funiq -f 2 file跳過欄位。忽略前 N 個欄位不進行比較。
-suniq -s 5 file跳過字元。忽略前 N 個字元不進行比較。
-wuniq -w 10 file限制長度。僅比較每一行前 N 個字元。
格式說明範例
sort | uniq去除所有重複行cat data.txt | sort | uniq
sort | uniq -c統計出現次數cat access.log | cut -f1 -d' ' | sort | uniq -c
sort | uniq -u找出不重複的資料sort emails.txt | uniq -u
sort | uniq -d找出有重複的資料sort ids.txt | uniq -d

Reference#

Official docs: