引言
如果你是Linux用戶,並且工作涉及處理和操作文本文件和字符串,那麼你應該已經熟悉了uniq命令,因為它是最常用的命令。
對於那些不熟悉uniq命令的人來說,它就是一個命令行工具,用於列印或忽略重複的字符串和行。
uniq過濾來自輸入(或stdin)的相鄰匹配行,並寫入到輸出(或stdout)。
如果沒有選項,匹配線將合併到第一個引用。
下面通過示例演示uniq的不同作用。
忽略重複項
下面是我們本文要處理和篩選的內容。
cat coder-helper.txt HelloHello How are you? How are you? Thank you Thank you
執行以下指令
uniq coder-helper.txt
輸出內容如下
Hello How are you? Thank you
顯示重複行數
使用-c參數,可以查看文件中的重複行計數。執行以下指令:
uniq -c coder-helper.txt
輸出內容如下:
2 Hello 2 How are you? 2 Thank you
僅列印有重複的行
為了演示此功能,我們將coder-helper.txt文本內添加一行內容,如下:
cat coder-helper.txt HelloHelloGood morning How are you? How are you? Thank you Thank you
通過使用-d參數,我們可以只選擇文件中重複的行。
uniq -d coder-helper.txt
輸出內容如下:
Hello How are you? Thank you
比較的時候忽略大小寫的區別
通常,當你使用uniq命令時,它會考慮字母的大小寫。但是如果想大小寫不敏感,可以使用-i參數。
假如我們的文本內容如下:
cat coder-helper.txt Hello hello How are you? How are you? Thank you thank you
執行以下命令:
uniq coder-helper.txt
輸出內容如下:
Hello hello How are you? Thank you thank you
再加上-i參數:
uniq -i coder-helper.txt
輸出內容如下:
Hello How are you? Thank you
大家看到了,輸出的是有重複行的第一行內容。且忽略了大小寫。
僅列印沒有重複行的內容
如果你只想查看文件中的唯一行,可以使用-u參數。假如原始內容如下:
cat coder-helper.txt Hello Hello Good morning How are you? How are you? Thank you Thank you Bye
執行以下指令:
uniq -u coder-helper.txt Good morning Bye
排序並查找重複項
有時,重複條目可能包含在文件的不同位置。
在這種情況下,如果我們簡單地使用uniq命令,它將不會檢測到不同行中的這些重複條目。
因此,我們首先需要對文件進行排序,然後才能找到重複項。
假如文本內容如下:
cat coder-helper.txt Adam Sara Frank John Ann Matt Harry Ann Frank John
我們使用管道,先排序文件,然後統計重複行計數。執行以下指令:
sort coder-helper.txt | uniq -c
輸出內容如下:
1 Adam 2 Ann 2 Frank 1 Harry 2 John 1 Matt 1 Sara
保存篩選內容到其他文件
當然可以使用管道重定向,但是uniq也提供了把篩選內容保存的文件的功能。假如內容如下:
cat coder-helper.txt Hello Hello How are you? Good morning Good morning Thank you
篩選出沒有重複的項:
uniq -u coder-helper.txt
輸出內容如下:
How are you? Thank you
uniq最後一個位置,定義的是輸出文件名。
uniq -u coder-helper.txt result.txt
查看並輸出result.txt內容。
cat result.txt How are you? Thank you
忽略開頭的字符
要忽略開頭的幾個字符,可以使用-s參數,但需要指定需要忽略的字符數。假如內容如下:
cat coder-helper.txt Aapple Bapple Cpears Dbanana Ebanana
我們忽略首字母進行排重:
uniq -s 1 coder-helper.txt
輸出內容如下:
Aapple Cpears Dbanana
寫在最後
配合管道符靈活運用,把uniq的功能發揮到極致吧。
Happy coding :-)