Find most frequent line in file in bash

2020-07-13 11:33发布

问题:

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).

回答1:

Kaizen ~

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

Kaylee 25

does this help ?



回答2:

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.



回答3:

awk -

awk '{a[$0]++; if(m<a[$0]){ m=a[$0];s[m]=$0}} END{print s[m]}' t.lis


回答4:

$ uniq -c list | sort -r | head -1 | awk '{$1=""}1'

Kaylee 25

Is this what you're looking for?



标签: bash lines