当前位置:首页 > 嵌入式 > 嵌入式教程
[导读]如果您经常用Linux处理和编辑文本文件、字符串等,那么您应该已经非常熟悉uniq命令了,因为它是该领域中使用最多的命令。

如果您经常用Linux处理和编辑文本文件、字符串等,那么您应该已经非常熟悉uniq命令了,因为它是该领域中使用最多的命令。

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

下面是使用uniq命令的几个例子。

举一些栗子

忽略重复项

在不指定任何参数的情况下执行uniq命令只会忽略重复的内容并显示惟一的字符串输出。

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

显示重复的行数

使用-c参数,可以查看文件中的重复行数

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参数,我们可以只选择文件中重复的行

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参数

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参数

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参数,但是需要指定需要忽略的字符数

foo@bar:~/Documents/files$ cat file1 1apple 2apple 3pears 4banana 5banana foo@bar:~/Documents/files$ uniq -s 1 file1 1apple 3pears 4banana

写在最后

好吧,这些都是过时的技术、过时的选择和几十年的程序!

但是,每天分散在我们命令行中,您都会无休止地执行管理员命令。

它是Linux系统的基石,也是经典的口碑,值得我们学习!

Happy coding :)

本站声明: 本文章由作者或相关机构授权发布,目的在于传递更多信息,并不代表本站赞同其观点,本站亦不保证或承诺内容真实性等。需要转载请联系该专栏作者,如若文章内容侵犯您的权益,请及时联系本站删除( 邮箱:macysun@21ic.com )。
换一批
延伸阅读
关闭