linux 下的文本处理——除去重复行uniq命令

xiaoxiao2021-03-01  9

原文地址:http://blog.51yip.com/shell/1022.html

一,uniq干什么用的

文本中的重复行,基本上不是我们所要的,所以就要去除掉。linux下有其他命令可以去除重复行,但是我觉得uniq还是比较方便的一个。使用uniq的时候要注意以下二点

1,对文本操作时,它一般会和sort命令进行组合使用,因为uniq 不会检查重复的行,除非它们是相邻的行。如果您想先对输入排序,使用sort -u。

2,对文本操作时,若域中为先空字符(通常包括空格以及制表符),然后非空字符,域中字符前的空字符将被跳过

二,uniq参数说明

[zhangy@BlackGhost~]$uniq--help 用法:uniq[选项]...[文件] 从输入文件或者标准输入中筛选相邻的匹配行并写入到输出文件或标准输出。 不附加任何选项时匹配行将在首次出现处被合并。 长选项必须使用的参数对于短选项时也是必需使用的。 -c,--count//在每行前加上表示相应行目出现次数的前缀编号 -d,--repeated//只输出重复的行 -D,--all-repeated//只输出重复的行,不过有几行输出几行 -f,--skip-fields=N//-f忽略的段数,-f1忽略第一段 -i,--ignore-case//不区分大小写 -s,--skip-chars=N//根-f有点像,不过-s是忽略,后面多少个字符-s5就忽略后面5个字符 -u,--unique//去除重复的后,全部显示出来,根mysql的distinct功能上有点像 -z,--zero-terminatedendlineswith0byte,notnewline -w,--check-chars=N//对每行第N个字符以后的内容不作对照 --help//显示此帮助信息并退出 --version//显示版本信息并退出

其中-z不知道有什么用

三,测试文本文件uniqtest

thisisatest thisisatest thisisatest iamtank ilovetank ilovetank thisisatest whomhaveatry WhoMhaveatry youhaveatry iwanttoabroad thosearegoodmen wearegoodmen

四,实例详解

[zhangy@BlackGhostmytest]$uniq-cuniqtest 3thisisatest 1iamtank 2ilovetank 1thisisatest//和第一行是重复的 1whomhaveatry 1WhoMhaveatry 1youhaveatry 1iwanttoabroad 1thosearegoodmen 1wearegoodmen

从上例子中我们可以看出,uniq的一个特性,检查重复行的时候,只会检查相邻的行。重复数据,肯定有很多不是相邻在一起的。

[zhangy@BlackGhostmytest]$sortuniqtest|uniq-c 1WhoMhaveatry 1iamtank 2ilovetank 1iwanttoabroad 4thisisatest 1thosearegoodmen 1wearegoodmen 1whomhaveatry 1youhaveatry

这样就可以解决上个例子中提到的问题

[zhangy@BlackGhostmytest]$uniq-d-cuniqtest 3thisisatest 2ilovetank

uniq -d 只显示重复的行

[zhangy@BlackGhostmytest]$uniq-Duniqtest thisisatest thisisatest thisisatest ilovetank ilovetank

uniq -D 只显示重复的行,并且把重复几行都显示出来。他不能和-c一起使用

[zhangy@BlackGhostmytest]$uniq-f1-cuniqtest 3thisisatest 1iamtank 2ilovetank 1thisisatest 2whomhaveatry 1youhaveatry 1iwanttoabroad 2thosearegoodmen//只有一行,显示二行

在这里those只有一行,显示的却是重复了,这是因为,-f 1 忽略了第一列,检查重复从第二字段开始的。

[zhangy@BlackGhostmytest]$uniq-i-cuniqtest 3thisisatest 1iamtank 2ilovetank 1thisisatest 2whomhaveatry//一个大写,一个小写 1youhaveatry 1iwanttoabroad 1thosearegoodmen 1wearegoodmen

检查的时候,不区分大小写

查看复制打印? [zhangy@BlackGhostmytest]$uniq-s4-cuniqtest 3thisisatest 1iamtank 2ilovetank 1thisisatest 3whomhaveatry//根上一个例子有什么不同 1iwanttoabroad 1thosearegoodmen 1wearegoodmen

检查的时候,不考虑前4个字符,这样whom have a try 就和 you have a try 就一样了。

[zhangy@BlackGhostmytest]$uniq-uuniqtest iamtank thisisatest whomhaveatry WhoMhaveatry youhaveatry iwanttoabroad thosearegoodmen wearegoodmen

去重复的项,然后全部显示出来

[zhangy@BlackGhostmytest]$uniq-w2-cuniqtest 3thisisatest 3iamtank 1thisisatest 1whomhaveatry 1WhoMhaveatry 1youhaveatry 1iwanttoabroad 1thosearegoodmen 1wearegoodmen

对每行第2个字符以后的内容不作检查,所以i am tank 根 i love tank就一样了。

转载请注明原文地址: https://www.6miu.com/read-3850070.html

最新回复(0)