uniq 指令功能為去除連續重複行,僅保留唯一記錄。以下透過實例詳細介紹常見用法。
預設合併連續重複行,只保留一行:
[root@stu100 ~]# cat test
boy took bat home
boy took bat home
girl took bat home
dog brought hat home
dog brought hat home
dog brought hat home
[root@stu100 ~]# uniq test
boy took bat home
girl took bat home
dog brought hat home
[root@stu100 ~]# uniq -c test
2 boy took bat home
1 girl took bat home
3 dog brought hat home
[root@stu100 ~]# uniq -d test
boy took bat home
dog brought hat home
[root@stu100 ~]# uniq -u test
girl took bat home
比較時忽略開頭若干欄位(欄位以空白分隔):
[root@stu100 ~]# uniq -f 1 test
boy took bat home
dog brought hat home
忽略第一欄位後,boy 與 girl 開頭的行視為連續重複而被合併。
[root@stu100 ~]# uniq -f 2 -s 2 test
boy took bat home
忽略前 2 欄位,並跳過第 2 空白後第 3 欄位首字元,最終比較「at home」。
注意:uniq 僅對連續重複行生效,若要處理整個檔案所有重複行,建議先用 sort 排序,再搭配 uniq 使用。