主要在命令行上工作並每天處理大量文本文件時要小心。 優衣庫 命令。
您可以使用 Uniq 命令輕鬆找到文件中的重複項和重複行。 uniq 不僅用於查找重複項,還用於刪除重複項、顯示重複行數、僅顯示重複行或僅顯示唯一行。
請注意,“uniq”命令不會檢測重複行,除非它們是相鄰的。因此,您可能需要先對它們進行排序或使用 uniq 中的 sort 命令來獲取結果。讓我給你一些例子。
uniq 命令是 GNU coreutils 軟件包的一部分,因此預裝在大多數 Linux 發行版上。因此,讓我們安裝它並查看 Uniq 命令的一些實際示例。
內容
uniq 命令示例
首先,讓我們創建一個包含重複行的文件。
$ 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
正如您在上面的文件中看到的,重複的行很少(第 1、第 2、第 3、第 5 行是重複的)。
1.使用uniq命令去除文件中連續的重複行
使用不帶參數的“uniq”命令會刪除所有連續的重複行並僅顯示唯一行。
$ uniq ostechnix.txt
樣本輸出:
如您所見,uniq 命令刪除了指定文件中所有連續的重複行。在上面的輸出中,您可能會注意到第 2 行和第 4 行仍然存在重複項。這是因為 uniq 命令只省略相鄰的重複行。當然,您也可以刪除這些不連續的重複項。請參見下面的第二個示例。
2.刪除所有重複行
$ sort ostechnix.txt | uniq
樣本輸出:
看?沒有重複或重複的行。也就是上面的命令會顯示文件中的所有行 ostechnix.txt
..
在上面的例子中,uniq 使用了 sort 命令。這是因為,如前所述,uniq 不會檢測重複/重複的行,除非它們是相鄰的。
3. 只顯示文件中唯一的行
要僅顯示文件中的唯一行,該命令如下所示:
$ sort ostechnix.txt | uniq -u
樣本輸出:
Linux is secure by default Top 500 super computers are powered by Linux
如您所見,特定文件中只有兩行。
4.只顯示重複的行
同樣,您可以在文件中顯示重複的行,如下所示。
$ sort ostechnix.txt | uniq -d
樣本輸出:
Linus is the creator of Linux. welcome to ostechnix
這兩個是 ostechnix.txt 文件中的重複/重複行。筆記 -d
(小寫 d) 只打印重複的行, 每組一個..印刷 所有重複行,使用 -D
(大寫d)如下。
$ sort ostechnix.txt | uniq -D
在下面的屏幕截圖中查看兩個標誌之間的區別。

5.顯示文件中每一行的出現次數
出於某種原因,您可能希望查看特定文件中某行重複了多少次。去做這個 -c
以下標誌。
$ 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
您還可以使用最常用的命令對每一行以及該行的出現次數進行排序和顯示。
$ 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”字符
您可以使用 Uniq 命令將比較限制為文件中特定數量的行字符。 -w
橫幅。例如,將比較限制為文件中一行的前四個字符並顯示重複行,如下所示:
$ uniq -d -w 4 ostechnix.txt
7.避免與第一個“N”字母比較
與限製文件中 N 字符行比較的方式相同,您可以使用以下命令避免第一個 N 字符比較: -s
橫幅。
以下命令避免與文件中一行的前四個字符進行比較。
$ uniq -d -s 4 ostechnix.txt
為避免比較第一個 N 字段而不是字符,請在上述命令中使用“-f”標誌。
有關詳細信息,請參閱幫助部分。
$ uniq --help
和手冊頁。
$ man uniq
- 初學者折疊命令教程
CLI 命令行 Linux Linux 命令 LinuxhowtoUniq 命令 Unix