Linux 技术手札

uniq 指令 – 去除重复资料

uniq 指令可以作用去除重复资料,对象可以是档案或者 pipe 管线输入。

uniq 去除重复资料时,只会对连续重复的行进行过滤处理,所以很多时 uniq 会配合 sort 指令一同使用,或者用 “sort -u” 实现。

uniq 使用例子:

例如有一个档案,里面的内容如下:

This is a testing.
This is a testing.
This is a testing.
This is also a testing.
This is also a testing.
This is line 3.

执行以下指令过滤重复内容:

$ uniq filename.txt

输出结果是:
This is a testing.
This is also a testing.
This is line 3.

如果上面的资料,每行重复的资料不是连续出现,可以先用 sort 进行排序,再用 uniq 过滤重复的部份,具体指令是:

$ sort filename.txt | uniq

以上执行 uniq 只会将结果直接输出,如果想将以上结果汇入到档案,可以用 pipe 做:

$ uniq filename >> new_filename.txt
Exit mobile version