Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find most frequent line in file in bash

Tags:

bash

lines

Suppose I have a file similar to as follows:

Abigail 85
Kaylee 25
Kaylee 25
kaylee
Brooklyn
Kaylee 25
kaylee 25

I would like to find the most repeated line, the output must be just the line.

I've tried

sort list | uniq -c

but I need clean output, just the most repeated line (in this example Kaylee 25).

like image 317
user1478993 Avatar asked Jun 04 '13 15:06

user1478993


3 Answers

Kaizen ~

$ sort zlist | uniq -c | sort -r | head -1|  xargs | cut -d" " -f2-

Kaylee 25

does this help ?

like image 77
AppleBee12 Avatar answered Oct 15 '22 17:10

AppleBee12


IMHO, none of these answers will sort the results correctly. The reason is that sort, without the -n, option will sort like this "1 10 11 2 3 4", etc., instead of "1 2 3 4 10 11 12". So, add -n like so:

sort zlist | uniq -c | sort -n -r | head -1

You can then, of course, pipe that to either xargs or sed as described earlier.

like image 35
Sina Bahram Avatar answered Oct 15 '22 19:10

Sina Bahram


awk -

awk '{a[$0]++; if(m<a[$0]){ m=a[$0];s[m]=$0}} END{print s[m]}' t.lis
like image 42
jim mcnamara Avatar answered Oct 15 '22 17:10

jim mcnamara