如何防止grep多次打印相同的字符串?

Tra*_*rae 20 command-line bash grep

如果我 grep 包含以下内容的文件:

These are words
These are words
These are words
These are words
Run Code Online (Sandbox Code Playgroud)

...对于 word These,它将打印字符串These are words四次。

如何防止 grep 多次打印重复字符串?否则,如何操作 grep 的输出来删除重复行?

Joh*_*024 29

Unix 的哲学是让工具做一件事并且把它们做好。在这种情况下,grep是从文件中选择文本的工具。要找出是否有重复,可以对文本进行排序。要删除重复项,可以使用-u选项sort. 因此:

grep These filename | sort -u
Run Code Online (Sandbox Code Playgroud)

sort有很多选择:见man sort。如果您想计算重复项或使用更复杂的方案来确定什么是重复项,那么将排序输出通过管道传送到uniq: grep These filename | sort | uniq并查看manuniq` 以获取选项。