天天看點

linux檔案處理之重複行處理,sort和uniq使用

1. uniq指令,

uniq隻能去掉連續重複的行

舉個栗子:

#cat test.txt

abcd
abcd
abcd
ddd
abcd
           

則執行cat test.txt | uniq後,結果為:

#cat test.txt | uniq

abcd
ddd
abcd
           

上面栗子列印出檔案中不同的行,如果希望列印出相同的行,則cat test.txt | uniq -d

#cat test.txt | uniq -d

abcd
           

2. sort指令

uniq隻能處理連續的行,如

#cat test.txt

abcd
ddd
abcd
aaa
abcd

#cat test.txt | uniq

abcd
ddd
abcd
aaa
abcd
           

如果希望去掉所有的重複行,則可以先使用sort指令對其進行排序,然後再處理。是以用sort能去掉不連續的行

舉個栗子:

#sort -u test.txt

abcd
ddd
           

上述指令也可以寫為:

#cat test.txt | sort | uniq 

abcd
ddd
           

後面處理就可以跟uniq指令一樣了,如擷取重複的行,可以寫為:

#cat test.txt | sort | uniq -d

abcd
           

繼續閱讀