首先,讓我們創(chuàng)建一個(gè)帶有一些重復(fù)行的文件:
vi ostechnix.txt
welcome to ostechnix
welcome to ostechnix
Linus is the creator of Linux.
Linux is secure by default
Linus is the creator of Linux.
Top 500 super computers are powered by Linux
正如你在上面的文件中看到的,我們有一些重復(fù)的行(第一行和第二行,第三行和第五行是重復(fù)的)。
1、 使用 uniq 命令刪除文件中的連續(xù)重復(fù)行
如果你在不使用任何參數(shù)的情況下使用 uniq 命令,它將刪除所有連續(xù)的重復(fù)行,只顯示唯一的行。
uniq ostechnix.txt
如你所見, uniq 命令刪除了給定文件中的所有連續(xù)重復(fù)行。你可能還注意到,上面的輸出仍然有第二行和第四行重復(fù)了。這是因?yàn)?uniq 命令只有在相鄰的情況下才會(huì)刪除重復(fù)的行,當(dāng)然,我們也可以刪除非連續(xù)的重復(fù)行。請(qǐng)看下面的第二個(gè)例子。
2、 刪除所有重復(fù)的行
sort ostechnix.txt | uniq
沒有重復(fù)的行。換句話說,上面的命令將顯示在 ostechnix.txt 中只出現(xiàn)一次的行。我們使用 sort 命令與 uniq 命令結(jié)合,因?yàn)椋拖裎姨岬降模侵貜?fù)行是相鄰的,否則 uniq 不會(huì)刪除它們。
3、 只顯示文件中唯一的一行
為了只顯示文件中唯一的一行,可以這樣做:
sort ostechnix.txt | uniq -u
示例輸出:
Linux is secure by default
Top 500 super computers are powered by Linux
如你所見,在給定的文件中只有兩行是唯一的。
4、 只顯示重復(fù)的行
同樣的,我們也可以顯示文件中重復(fù)的行,就像下面這樣:
sort ostechnix.txt | uniq -d
示例輸出:
Linus is the creator of Linux.
welcome to ostechnix
這兩行在 ostechnix.txt 文件中是重復(fù)的行。請(qǐng)注意 -d(小寫 d) 將會(huì)只打印重復(fù)的行,每組顯示一個(gè)。打印所有重復(fù)的行,使用 -D(大寫 D),如下所示:
sort ostechnix.txt | uniq -D
5、 顯示文件中每一行的出現(xiàn)次數(shù)
由于某種原因,你可能想要檢查給定文件中每一行重復(fù)出現(xiàn)的次數(shù)。要做到這一點(diǎn),使用 -c 選項(xiàng),如下所示:
sort ostechnix.txt | uniq -c
示例輸出:
2 Linus is the creator of Linux.
1 Linux is secure by default
1 Top 500 super computers are powered by Linux
2 welcome to ostechnix
我們還可以按照每一行的出現(xiàn)次數(shù)進(jìn)行排序,然后顯示,如下所示:
sort ostechnix.txt | uniq -c | sort -nr
示例輸出:
2 welcome to ostechnix
2 Linus is the creator of Linux.
1 Top 500 super computers are powered by Linux
1 Linux is secure by default
6、 將比較限制為 N 個(gè)字符
我們可以使用 -w 選項(xiàng)來限制對(duì)文件中特定數(shù)量字符的比較。例如,讓我們比較文件中的前四個(gè)字符,并顯示重復(fù)行,如下所示:
uniq -d -w 4 ostechnix.txt
7、 忽略比較指定的 N 個(gè)字符
像對(duì)文件中行的前 N 個(gè)字符進(jìn)行限制比較一樣,我們也可以使用 -s 選項(xiàng)來忽略比較前 N 個(gè)字符。
下面的命令將忽略在文件中每行的前四個(gè)字符進(jìn)行比較:
uniq -d -s 4 ostechnix.txt
為了忽略比較前 N 個(gè)字段(LCTT 譯注:即前幾列)而不是字符,在上面的命令中使用 -f 選項(xiàng)。
欲了解更多詳情,請(qǐng)參考幫助部分:
uniq --help
也可以使用 man 命令查看:
man uniq