LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   bash script that counts string occurrence (https://www.linuxquestions.org/questions/programming-9/bash-script-that-counts-string-occurrence-704078/)

tikit 02-12-2009 01:13 AM

bash script that counts string occurrence
 
Hi,

I have a file with names:

Code:

John
Mary
Bob
Mary
Mary
Bob

and I am searching for an efficient way how to summarize every name ocurrence like this:

Code:

Mary - 3
Bob - 2
John - 1

I tried this:
1. sorted the file
2. removed duplicate lines using uniq and saved to a temp file
3. went through this file and used
Code:

grep -c $LINE file_with_names
to make the sum

It works but It seams to complicated for me. Is there a simplier solution? An one line command would be fine.

theYinYeti 02-12-2009 02:26 AM

Code:

… | sort | uniq -c
Yves.

twantrd 02-12-2009 02:26 AM

Code:

[twantrd@twantrd tmp]$ cat names | sort | uniq -c
      2 Bob
      1 John
      3 Mary

-twantrd

jan61 02-12-2009 11:09 AM

Moin,

Code:

sort names | uniq -c
no need for a cat.

Jan


All times are GMT -5. The time now is 05:28 AM.