老掉牙的Linux uniq還能這麼玩兒!悲憤網友:以前都白學了!

引言

如果你是一個Linux用戶,並且工作涉及到處理和操作文本文件和字符串,那麼你應該已經熟悉uniq命令了,因為它是該領域最常用的命令。

對於不熟悉uniq命令的人來說,它就是一個命令行工具,用於打印或省略重複的行。這基本上是從輸入中過濾相鄰的匹配行,然後寫入輸出。如果沒有選項,則將匹配的行合併到第一個出現的行。

下面是使用uniq命令的幾個例子。

老掉牙的Linux uniq還能這麼玩兒!悲憤網友:以前都白學了!

舉一些栗子

忽略重複項

在不指定任何參數的情況下執行uniq命令只會忽略重複的內容並顯示惟一的字符串輸出。

<code>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 How are you? Thank you/<code>

顯示重複的行數

使用-c參數,可以查看文件中的重複行數

<code>foo@bar

:~/Documents/files

$ cat file1 Hello Hello How are you? How are you? Thank you Thank you foor@bar

:~/Documents/files

$ uniq -c file1

2

Hello

2

How are you?

2

Thank you/<code>

僅輸出有重複的行

通過使用-d參數,我們可以只選擇文件中重複的行

<code>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/<code>

比較時忽略大小寫

通常,當您使用uniq命令時,它會考慮字母的情況。但是如果你想忽略這種情況,你可以使用-i參數

<code>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/<code>

只打印唯一行

如果只想查看文件中的唯一行,可以使用-u參數

<code>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/<code>

對重複項進行排序和查找

有時,重複的條目可能包含在文件的不同位置。在這種情況下,如果我們簡單地使用uniq命令,它將不會在不同的行中檢測到這些重複的條目。在這種情況下,我們首先需要將文件排序,然後找到重複項。

<code>foo@bar

:~/Documents/files

$ cat file1 Adam Sara Frank John Ann Matt Harry Ann Frank John foo@bar

:~/Documents/files

$ sort file1

| uniq -c 1 Adam 2 Ann 2 Frank 1 Harry 2 John 1 Matt 1 Sara

/<code>

將輸出保存到文件中

我們的uniq命令的輸出可以簡單地保存在另一個文件中,如下所示

<code>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 output foo@bar

:~/Documents/files

$ cat output How are you? Thank you/<code>

忽略開頭N個字符

為了在開始時忽略幾個字符,可以使用-s參數,但是需要指定需要忽略的字符數

<code>foo@bar

:~/Documents/files

$ cat file1

1

apple

2

apple

3

pears

4

banana

5

banana foo@bar

:~/Documents/files

$ uniq -s

1

file1

1

apple

3

pears

4

banana/<code>


寫在最後

好吧,都是老古董的技術,都是老掉牙的選項,都是幾十年的老程序!

可是每天都穿插在我們的命令行中,孜孜不倦,穩定地執行著管理員的命令。

這是Linux系統的基石,是經典流傳的口碑,值得我們仔細掌握倒背如流!

Happy coding :)


我是 @程序員小助手 ,持續分享編程故事,歡迎關注。


分享到:


相關文章: