如果您經(jīng)常用Linux處理和編輯文本文件、字符串等,那么您應該已經(jīng)非常熟悉uniq命令了,因為它是該領域中使用最多的命令。
對于不熟悉uniq命令的人來說,它就是一個命令行工具,用于打印或省略重復的行。這基本上是從輸入中過濾相鄰的匹配行,然后寫入輸出。如果沒有選項,則將匹配的行合并到第一個出現(xiàn)的行。
下面是使用uniq命令的幾個例子。
舉一些栗子
忽略重復項
在不指定任何參數(shù)的情況下執(zhí)行uniq命令只會忽略重復的內(nèi)容并顯示惟一的字符串輸出。
foo@bar:~/Documents/files$cat file1 HelloHello How are you? How are you? Thank you Thank you foo@bar:~/Documents/files$ uniq file1 Hello How are you? Thank you
顯示重復的行數(shù)
使用-c參數(shù),可以查看文件中的重復行數(shù)
foo@bar:~/Documents/files$ cat file1 Hello Hello How are you? How are you? Thank you Thank you foor@bar:~/Documents/files$ uniq -c file12 Hello 2 How are you? 2 Thank you
僅輸出有重復的行
通過使用-d參數(shù),我們可以只選擇文件中重復的行
foo@bar:~/Documents/files$ cat file1 Hello Hello Good morning How are you? How are you? Thank you Thank you Bye foo@bar:~/Documents/files$ uniq -d file1 Hello How are you? Thank you
比較時忽略大小寫
通常,當您使用uniq命令時,它會考慮字母的情況。但是如果你想忽略這種情況,你可以使用-i參數(shù)
foo@bar:~/Documents/files$ cat file1 Hello hello How are you? How are you? Thank you thank you foo@bar:~/Documents/files$ uniq file1 Hello hello How are you? Thank you thank you foo@bar:~/Documents/files$ uniq -i file1 Hello How are you? Thank you
只打印唯一行
如果只想查看文件中的唯一行,可以使用-u參數(shù)
foo@bar:~/Documents/files$ cat file1 Hello Hello Good morning How are you? How are you? Thank you Thank you Bye foo@bar:~/Documents/files$ uniq -u file1 Good morning Bye
對重復項進行排序和查找
有時,重復的條目可能包含在文件的不同位置。在這種情況下,如果我們簡單地使用uniq命令,它將不會在不同的行中檢測到這些重復的條目。在這種情況下,我們首先需要將文件排序,然后找到重復項。
foo@bar:~/Documents/files$ cat file1 Adam Sara Frank John Ann Matt Harry Ann Frank John foo@bar:~/Documents/files$ sort file1 | uniq -c1 Adam 2 Ann 2 Frank 1 Harry 2 John 1 Matt 1 Sara
將輸出保存到文件中
我們的uniq命令的輸出可以簡單地保存在另一個文件中,如下所示
foo@bar:~/Documents/files$ cat file1 Hello Hello How are you? Good morning Good morning Thank you foo@bar:~/Documents/files$ uniq -u file1 How are you? Thank you foo@bar:~/Documents/files$ uniq -u file1 outputfoo@bar:~/Documents/files$ cat output How are you? Thank you
忽略開頭N個字符
為了在開始時忽略幾個字符,可以使用-s參數(shù),但是需要指定需要忽略的字符數(shù)
foo@bar:~/Documents/files$ cat file1 1apple 2apple 3pears 4banana 5banana foo@bar:~/Documents/files$ uniq -s 1 file1 1apple 3pears 4banana
寫在最后
好吧,這些都是過時的技術、過時的選擇和幾十年的程序!
但是,每天分散在我們命令行中,您都會無休止地執(zhí)行管理員命令。
它是Linux系統(tǒng)的基石,也是經(jīng)典的口碑,值得我們學習!
Happy coding :)





