Kartik Deshpande Kartik Deshpande - 5 months ago 9
Bash Question

Print duplicate entries in a file using linux commands

I have a file called foo.txt, which consists of:

abc
zaa
asd
dess
zaa
abc
aaa
zaa


I want the output to be stored in another file as:

this text abc appears 2 times
this text zaa appears 3 times


I have tried the following command, but this just writes duplicate entries and their number.

sort foo.txt | uniq --count --repeated > sample.txt


Example of output of above command:

abc 2
zaa 3


How do I add the line "this text appears x times" ?

Answer

Awk is your friend:

sort foo.txt | uniq --count --repeated | awk '{print($2" appears "$1" times")}'