开启辅助访问 切换到窄版

打印 上一主题 下一主题

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

[复制链接]
作者:达益IPHONE 
版块:
嵌入式操作系统 linux 发布时间:2020-4-25 22:57:06
14070
楼主
跳转到指定楼层
| 只看该作者 回帖奖励 |倒序浏览 |阅读模式
引言

如果你是一个Linux用户,并且工作涉及到处理和操作文本文件和字符串,那么你应该已经熟悉uniq命令了,因为它是该领域最常用的命令。
对于不熟悉uniq命令的人来说,它就是一个命令行工具,用于打印或省略重复的行。这基本上是从输入中过滤相邻的匹配行,然后写入输出。如果没有选项,则将匹配的行合并到第一个出现的行。
下面是使用uniq命令的几个例子。


举一些栗子

忽略重复项
在不指定任何参数的情况下执行uniq命令只会忽略重复的内容并显示惟一的字符串输出。
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
显示重复的行数
使用-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 file1
2 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 -c
1 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 output
foo@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 :)
我是 @程序员小助手 ,持续分享编程故事,欢迎关注。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有帐号?立即注册

回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

快速回复 返回顶部 返回列表