uniq#
uniq 是包含在 GNU Coreutils 內的文字去重工具。
uniq 是 Linux 系統中用於報告或過濾檔案中「連續重複行」的指令。它通常與 sort 指令搭配使用,因為 uniq 只能偵測相鄰的重複行。透過 uniq,你可以快速找出重複資料、統計出現次數或僅顯示唯一的內容。
Install#
$ sudo apt install coreutilsSetting in up#
Operate#
uniq [options] [file]
先排序後去重(最常見用法)#
sort file.txt | uniq
統計各行出現次數#
sort file.txt | uniq -c
僅顯示有重複過的行#
sort file.txt | uniq -d
| 參數 | 範例指令 | 說明 |
|---|---|---|
-c | uniq -c file | 計數。在每一行前面顯示該行重複出現的次數。 |
-d | uniq -d file | 顯示重複。僅輸出檔案中重複出現過的內容。 |
-u | uniq -u file | 顯示唯一。僅輸出檔案中「從未重複」過的內容。 |
-i | uniq -i file | 忽略大小寫。比較時不區分英文字母大小寫。 |
-f | uniq -f 2 file | 跳過欄位。忽略前 N 個欄位不進行比較。 |
-s | uniq -s 5 file | 跳過字元。忽略前 N 個字元不進行比較。 |
-w | uniq -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: