简体   繁体   中英

Output and count total number of occurrences using grep in linux/nix

I have a data file ( users.dat) with entries like:

user1
user2
user4
user1
user2
user1
user4
...
user3
user2

which command I should ( grep? wc?) use to count how many times each word repeats and output it to user_total.dat like this:

user1 80
user2 35
user3 18
user4 120

the issue is that I cannot specify "user1" or "user19287" because there are too many users with random, but repeating numbers.

But there are repeating users in that DAT file.

Thanks for your help!!!

Use the uniq command to count the repetitions of a line. It requires the input to be sorted, so use sort first.

sort users.dat | uniq -c > user_total.dat
sort <users.dat | uniq -c > user_total.dat

If you want it further in order of occurance pass it through sort a 2nd time using some form the -n argument (read man page on that).

(on edit: bah... didn't realize how dumb the system rendered that bit of code)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM