开启辅助访问 切换到窄版

打印 上一主题 下一主题

鹤立鸡群!用Linuxuniq一眼找出不一样的那行

[复制链接]
作者:热茶の小曲 
版块:
嵌入式操作系统 linux 发布时间:2020-4-11 08:42:46
14500
楼主
跳转到指定楼层
| 只看该作者 回帖奖励 |倒序浏览 |阅读模式
引言

如果你是Linux用户,并且工作涉及处理和操作文本文件和字符串,那么你应该已经熟悉了uniq命令,因为它是最常用的命令。
对于那些不熟悉uniq命令的人来说,它就是一个命令行工具,用于打印或忽略重复的字符串和行。
uniq过滤来自输入(或stdin)的相邻匹配行,并写入到输出(或stdout)。
如果没有选项,匹配线将合并到第一个引用。
下面通过示例演示uniq的不同作用。




忽略重复项

下面是我们本文要处理和筛选的内容。
cat coder-helper.txt
Hello Hello
How are you?
How are you?
Thank you
Thank you
执行以下指令
uniq coder-helper.txt
输出内容如下
Hello
How are you?
Thank you
显示重复行数

使用-c参数,可以查看文件中的重复行计数。执行以下指令:
uniq -c coder-helper.txt
输出内容如下:
2 Hello
2 How are you?
2 Thank you
仅打印有重复的行

为了演示此功能,我们将coder-helper.txt文本内添加一行内容,如下:
cat coder-helper.txt
Hello
Hello
Good morning
How are you?
How are you?
Thank you
Thank you
通过使用-d参数,我们可以只选择文件中重复的行。
uniq -d coder-helper.txt
输出内容如下:
Hello
How are you?
Thank you
比较的时候忽略大小写的区别

通常,当你使用uniq命令时,它会考虑字母的大小写。但是如果想大小写不敏感,可以使用-i参数。
假如我们的文本内容如下:
cat coder-helper.txt
Hello
hello
How are you?
How are you?
Thank you
thank you
执行以下命令:
uniq coder-helper.txt
输出内容如下:
Hello
hello
How are you?
Thank you
thank you
再加上-i参数:
uniq -i coder-helper.txt
输出内容如下:
Hello
How are you?
Thank you
大家看到了,输出的是有重复行的第一行内容。且忽略了大小写。
仅打印没有重复行的内容

如果你只想查看文件中的唯一行,可以使用-u参数。假如原始内容如下:
cat coder-helper.txt
Hello
Hello
Good morning
How are you?
How are you?
Thank you
Thank you
Bye
执行以下指令:
uniq -u coder-helper.txt
Good morning
Bye
排序并查找重复项

有时,重复条目可能包含在文件的不同位置。
在这种情况下,如果我们简单地使用uniq命令,它将不会检测到不同行中的这些重复条目
因此,我们首先需要对文件进行排序,然后才能找到重复项。
假如文本内容如下:
cat coder-helper.txt
Adam
Sara
Frank
John
Ann
Matt
Harry
Ann
Frank
John
我们使用管道,先排序文件,然后统计重复行计数。执行以下指令:
sort coder-helper.txt | uniq -c
输出内容如下:
1 Adam
2 Ann
2 Frank
1 Harry
2 John
1 Matt
1 Sara
保存筛选内容到其他文件

当然可以使用管道重定向,但是uniq也提供了把筛选内容保存的文件的功能。假如内容如下:
cat coder-helper.txt
Hello
Hello
How are you?
Good morning
Good morning
Thank you
筛选出没有重复的项:
uniq -u coder-helper.txt
输出内容如下:
How are you?
Thank you
uniq最后一个位置,定义的是输出文件名。
uniq -u coder-helper.txt result.txt
查看并输出result.txt内容。
cat result.txt
How are you?
Thank you
忽略开头的字符

要忽略开头的几个字符,可以使用-s参数,但需要指定需要忽略的字符数。假如内容如下:
cat coder-helper.txt
Aapple
Bapple
Cpears
Dbanana
Ebanana
我们忽略首字母进行排重:
uniq -s 1 coder-helper.txt
输出内容如下:
Aapple
Cpears
Dbanana
写在最后

配合管道符灵活运用,把uniq的功能发挥到极致吧。
Happy coding :-)

本帖子中包含更多资源

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

回复

使用道具 举报

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

本版积分规则

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