当前位置: 首页 > Linux

回顾Linux命令去重uniq

时间:2023-04-06 21:11:48 Linux

uniq也是Linux管道命令家族的一员,主要作用是去重。在介绍uniq命令之前,我们先来创建文件/tmp/uniq.txt,在下面的情况下会用到。内容如下:默认情况下,uniq只会取相邻的重复数据进行去重。虽然/tmp/uniq.txt中有3个“onmpw网站”条目,但其中一个与另外两个不相邻,因此只删除了一个。“errorphpfunction”也是如此。鉴于上述检索机制,uniq一般应与sort命令一起使用。#排序1.txt|uniqalphacsswebcatlinuxcommandererrorphpfunctionhelloworldonmpwwebsiterecruisepagesiterepeatnodatawellowebsite现在让我们看看是否所有重复的项目都被删除了。好了,经过小测试,我们先简单介绍一下uniq命令的选项。-c统计每行数据排序1.txt的重复次数|uniq-calphacsswebcatlinuxcommandererrorphpfunctionhelloworldonmpwwebsiterecruisepagesiterepeatnodatawellowebsite我们看到“errorphpfunction”出现了两次,“onmpwwebsite”出现了三次。其余的没有重复,所以是1。-i忽略大小写在1.txtcat1.txttalphacsswebcatlinuxcommandererrorphpfunctionhelloworldonmpwwebsiteonmpwwebsitewellowebsiteErrorPHPfunctionrecruisepagesiteerrorphpfunctionrepeatnodataonmpw1.txtwebsite–calpha中添加一行数据“ErrorPHPfunction”csswebcatlinuxcommandererrorphpfunctionErrorPHPfunctionhelloworldonmpwwebsiterecruisepagesiterepeatnodatawellowebsite看看结果吧,uniq默认是区分大小写的。使用-i忽略大小写问题sort1.txt|uniq–c–ialphacsswebcatlinuxcommandererrorphpfunctionhelloworldonmpwwebsiterecruisepagesiterepeatnodatawellowebsite现在检查大小写是否被忽略。-u只输出不重复排序的数据1.txt|uniq–iualphacsswebcatlinuxcommandhelloworldrecruisepagesiterepeatnodatawellowebsite看到没有输出结果中的“errorphpfunction”和“onmpwwebsite”。-wN表示从第一个字符开始只取N个字符来确定权重。排序1.txt|uniq–iw2alphacsswebcatlinuxcommandererrorphpfunctionhelloworldonmpwwebsiterecruisepagesitewellowebsite这里我们让uniq只搜索前两个字符,recruit和repeat的前两个字符是re,所以这两行也算重复。-fN表示跳过前N个字段,从第N+1个字段开始取重复数据。使用空格或制表符作为分隔符。排序1.txt|uniq–icf2alphacsswebcatlinuxcommandererrorphpfunctionhelloworldonmpwwebsiterepeatnodatawellowebsite从结果我们可以看到,前两个字段被跳过,从第三个字段判断权重。“recruisepagesite”第三个字段和“onmpwwebsite”是一样的,所以认为是同一个数据。但是我们看到“wellowebsite”和“onmpwwebsite”不仅有相同的第三字段,而且还有第二字段。那么为什么它不计入“onmpw网站”的重复项中。对于这个问题,我们还是回到前面说的,uniq只是检测相邻数据是否重复。要解决这个问题还需要从排序命令入手。还记得sort命令的-k选项吗,没错,我们就用它来解决。排序-k21.txt|uniq–icf2alphacsswebcatlinuxcommandrepeatnodatarecruisepagesiteerrorphpfunctiononmpwwebsitehelloworld让我们看看是否解决了。-sN表示跳过前N个字符。我们不会在这里给出这个选项的例子。该选项的用法与-fN类似,只是-fN是跳过前N个字段;-s是跳过前N个字符。-d只输出第一项重复的数据。排序1.txt|uniq-idw2repeatnodataerrorphpfunctiononmpwwebsite结果只有这三个。为什么会有“repeatnodata”的数据,注意这里-w2的应用。-D输出所有重复排序1.txt|uniq–iDw2sort1.txt|uniq–iDw2repeatnodatarecruisepagesiteerrorphpfunctionerrorphpfunctionErrorPHPfunctiononmpwwebsiteonmpwwebsiteonmpwwebsite好了,关于uniq选项的所有常用信息命令都介绍完了。有关uniq的更多详细信息,请使用命令infouniq。