使用Linux中使用UNIQ命令的方法
时间:2020-03-05 15:28:57 来源:igfitidea点击:
如果我们是Linux用户,工作涉及使用和操作文本文件和字符串,那么我们应该已经熟悉了UNIQ命令,因为它最常用于该区域。
对于那些不熟悉UNIQ命令的人,它是用于报告或者省略重复字符串或者行的命令行工具。
这基本上从输入(或者标准输入)过滤相邻的匹配线,并写入输出(或者标准输出)。
没有任何选项,匹配线被合并到第一次出现。
以下是UNIQ命令的使用示例
1)省略重复
执行UNIQ命令而不指定任何参数,只会省略重复并显示唯一的字符串输出。
fluser@fvm:~/Documents/files$cat file1 Hello Hello How are you? How are you? Thank you Thank you fluser@fvm:~/Documents/files$uniq file1 Hello How are you? Thank you
2)显示重复线路的数量
使用-c参数,可以在文件中查看重复的行计数
fluser@fvm:~/Documents/files$cat file1 Hello Hello How are you? How are you? Thank you Thank you fluser@fvm:~/Documents/files$uniq -c file1 2 Hello 2 How are you? 2 Thank you
3)仅打印重复项
通过使用-d参数,我们只能选择在文件中复制的行
fluser@fvm:~/Documents/files$cat file1 Hello Hello Good morning How are you? How are you? Thank you Thank you Bye fluser@fvm:~/Documents/files$uniq -d file1 Hello How are you? Thank you
4)比较时忽略案例
通常,当我们使用Uniq命令时,它会考虑仔细考虑字母。
但是,如果要忽略这种情况,则可以使用-i参数
fluser@fvm:~/Documents/files$cat file1 Hello hello How are you? How are you? Thank you thank you fluser@fvm:~/Documents/files$uniq file1 Hello hello How are you? Thank you thank you fluser@fvm:~/Documents/files$uniq -i file1 Hello How are you? Thank you
5)只打印唯一线
如果我们只想看到文件中的唯一行,则可以使用-u参数
fluser@fvm:~/Documents/files$cat file1 Hello Hello Good morning How are you? How are you? Thank you Thank you Bye fluser@fvm:~/Documents/files$uniq -u file1 Good morning Bye
6)排序并查找重复
有时重复条目可能包含在文件的不同位置。
在这种情况下,如果我们只使用UNIQ命令,它不会检测到不同行中的这些重复条目。
在这种情况下,我们首先需要对文件进行排序,然后我们可以找到重复
fluser@fvm:~/Documents/files$cat file1 Adam Sara Frank John Ann Matt Harry Ann Frank John fluser@fvm:~/Documents/files$sort file1 | uniq -c 1 Adam 2 Ann 2 Frank 1 Harry 2 John 1 Matt 1 Sara
7)将输出保存在另一个文件中
我们的UNIQ命令的输出可以简单地保存在另一个文件中如下所示
fluser@fvm:~/Documents/files$cat file1 Hello Hello How are you? Good morning Good morning Thank you fluser@fvm:~/Documents/files$uniq -u file1 How are you? Thank you fluser@fvm:~/Documents/files$uniq -u file1 output fluser@fvm:~/Documents/files$cat output How are you? Thank you
8)忽略角色
为了忽略开头的几个字符,我们可以使用-s参数,但我们需要指定忽略所需的字符数
fluser@fvm:~/Documents/files$cat file1 1apple 2apple 3pears 4banana 5banana fluser@fvm:~/Documents/files$uniq -s 1 file1 1apple 3pears 4banana