If I grep a file containing the following:
These are words
These are words
These are words
These are words
…for the word These
, it will print the string These are words
four times.
How can I prevent grep from printing recurring strings more than once? Otherwise, how can I manipulate the output of grep to remove duplicate lines?
Best Answer
The Unix philosophy is to have tools that do one thing and do them well. In this case,
grep
is the tool that selects text from a file. To find out if there are duplicates, one sorts the text. To remove the duplicates, one uses the-u
option tosort
. Thus:sort
has many options: seeman sort
. If you want to count duplicates or have a more complicated scheme for determining what is or is not a duplicate, then pipe the sort output touniq
:grep These filename | sort | uniq
and seeman
uniq` for options.