uniq 命令用於檢查及刪除文本文件中重復出現的行列,一般與 sort 命令結合使用。
uniq 可檢查文本文件中重復出現的行列。
命令語法:
uniq [-c/d/D/u/i] [-f Fields] [-s N] [-w N] [InFile] [OutFile]
參數解釋:
-c: 在每列旁邊顯示該行重復出現的次數。
-d: 僅顯示重復出現的行列,顯示一行。
-D: 顯示所有重復出現的行列,有幾行顯示幾行。
-u: 僅顯示出一次的行列
-i: 忽略大小寫字符的不同
-f Fields: 忽略比較指定的列數。
-s N: 忽略比較前面的N個字符。
-w N: 對每行第N個字符以后的內容不作比較。
[InFile]: 指定已排序好的文本文件。如果不指定此項,則從標准讀取數據;
[OutFile]: 指定輸出的文件。如果不指定此選項,則將內容顯示到標准輸出設備(顯示終端)。
栗子
# uniq.txt
My name is Delav My name is Delav My name is Delav I'm learning Java I'm learning Java I'm learning Java who am i Who am i Python is so simple My name is Delav That's good That's good And studying Golang
1. 直接去重
uniq uniq.txt
結果為:
My name is Delav I'm learning Java who am i Who am i Python is so simple My name is Delav That's good And studying Golang
2. 顯示重復出現的次數
uniq -c uniq.txt
結果為:
3 My name is Delav 3 I'm learning Java 1 who am i 1 Who am i 1 Python is so simple 1 My name is Delav 2 That's good 1 And studying Golang
你會發現,上面有兩行 ”My name is Delav ” 是相同的。也就是說,當重復的行不相鄰時,uniq 命令是不起作用的。所以,經常需要跟 sort 命令一起使用。
sort uniq.txt | uniq -c
結果為:
1 And studying Golang 3 I'm learning Java 4 My name is Delav 1 Python is so simple 2 That's good 1 who am i 1 Who am i
3. 只顯示重復的行,並顯示重復次數
uniq -cd uniq.txt
結果為:
3 My name is Delav 3 I'm learning Java 2 That's good
顯示所有重復的行,不能與 -c 一起使用
uniq -D uniq.txt
結果為:
My name is Delav My name is Delav My name is Delav I'm learning Java I'm learning Java I'm learning Java That's good That's good
4. 忽略第幾列字符
下面這里 -f 1 忽略了第一列字符,所以"who am i" 和 "Who am i" 判定為重復
uniq -c -f 1 uniq.txt
結果為:
3 My name is Delav 3 I'm learning Java 2 who am i 1 Python is so simple 1 My name is Delav 2 That's good 1 And studying Golang
5. 忽略大小寫
下面這里 -i 忽略了大小寫,所以"who am i" 和 "Who am i" 判定為重復
uniq -c -i uniq.txt
結果為:
3 My name is Delav 3 I'm learning Java 2 who am i 1 Python is so simple 1 My name is Delav 2 That's good 1 And studying Golang
6. 忽略前面N個字符
下面這里 -s 4 表示忽略前面四個字符,所以"who am i" 和 "Who am i" 判定為重復
uniq -c -s 4 uniq.txt
結果為:
3 My name is Delav 3 I'm learning Java 2 who am i 1 Python is so simple 1 My name is Delav 2 That's good 1 And studying Golang
7. 忽略第N個字符后的內容
uniq -c -w 2 uniq.txt