老掉牙的Linux uniq还能这么玩儿!悲愤网友:以前都白学了!

引言

如果你是一个Linux用户,并且工作涉及到处理和操作文本文件和字符串,那么你应该已经熟悉uniq命令了,因为它是该领域最常用的命令。

对于不熟悉uniq命令的人来说,它就是一个命令行工具,用于打印或省略重复的行。这基本上是从输入中过滤相邻的匹配行,然后写入输出。如果没有选项,则将匹配的行合并到第一个出现的行。

下面是使用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 :)


我是 @程序员小助手 ,持续分享编程故事,欢迎关注。