下面是我们本文要处理和筛选的内容。
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
忽略开头的字符