LinuxQuestions.org
Review your favorite Linux distribution.
Home Forums Tutorials Articles Register
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 02-12-2009, 01:13 AM   #1
tikit
Member
 
Registered: Feb 2008
Posts: 85

Rep: Reputation: 16
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.
 
Old 02-12-2009, 02:26 AM   #2
theYinYeti
Senior Member
 
Registered: Jul 2004
Location: France
Distribution: Arch Linux
Posts: 1,897

Rep: Reputation: 66
Code:
… | sort | uniq -c
Yves.
 
Old 02-12-2009, 02:26 AM   #3
twantrd
Senior Member
 
Registered: Nov 2002
Location: CA
Distribution: redhat 7.3
Posts: 1,440

Rep: Reputation: 52
Code:
[twantrd@twantrd tmp]$ cat names | sort | uniq -c
      2 Bob
      1 John
      3 Mary
-twantrd

Last edited by twantrd; 02-12-2009 at 02:27 AM. Reason: LOL, just posted right after YinYeti
 
Old 02-12-2009, 11:09 AM   #4
jan61
Member
 
Registered: Jun 2008
Posts: 235

Rep: Reputation: 47
Moin,

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

Jan
 
  


Reply



Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
Bash Script to get the first characters of a string onesikgypo Programming 12 11-14-2008 09:57 AM
how to find and replace only the 2nd occurrence of similar string in a file hchoonbeng Linux - Newbie 1 10-08-2008 03:44 AM
SED replace string by occurrence uttam_h Programming 5 03-05-2008 10:02 PM
help with bash script: remove * to the last . in string drkstr Linux - Software 3 04-25-2006 04:54 PM
looking for string on particular line - bash script tara Linux - General 9 12-14-2005 05:43 PM

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 01:39 PM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration