1751948 Members
4732 Online
108783 Solutions
New Discussion юеВ

find the count

 
SOLVED
Go to solution
Rahul_13
Advisor

find the count

Hi,

I have parsed a number of files for the value on a particular field and stored it in a file. Now I want to know the count of each pattern that is stored in the file. For example, the entries in the file has

abc
abc
abc
def
xyz
xyz
123
123
...

and so on. I want to get the count of the occurance of each values. Say, abc - 3 times, 123 - 5 times etc.

Can anyone please help me

Thanks,
Rahul
11 REPLIES 11
Sundar_7
Honored Contributor

Re: find the count

grep with -c option will tell you the count

# grep -c "abc" inputfile
Learn What to do ,How to do and more importantly When to do ?
Geoff Wild
Honored Contributor

Re: find the count

Bingo! - Sundar has it.


Another way , pipe to wc

grep "abc" somefile |wc

Rgds...Geoff
Proverbs 3:5,6 Trust in the Lord with all your heart and lean not on your own understanding; in all your ways acknowledge him, and he will make all your paths straight.
Prashant Zanwar_4
Respected Contributor

Re: find the count

grep pattern | wc -l

this is easiest way to acheive this.
And if you know pattern, you can do some more things of your linking, like

count=1
cat filename | while read line
echo $line
if [ $line = $pattern ]
((count=count+1))
done
something like above you may like to do.
Hope the above helps
Prashant
"Intellect distinguishes between the possible and the impossible; reason distinguishes between the sensible and the senseless. Even the possible can be senseless."
john korterman
Honored Contributor

Re: find the count

Hi,
if the lines are adjacant as in your example, you can also try the uniq command, e.g.
# uniq -c
3 abc
1 def
2 xyz
2 123

regards,
John K.
it would be nice if you always got a second chance
Mike Stroyan
Honored Contributor

Re: find the count

The general case solution is
sort file | uniq -c
to get a count for each unique line in file.

You can push that through one more sort to order the patterns by frequency.
sort file | uniq -c | sort -bn
Rahul_13
Advisor

Re: find the count

Hi,

The values can be anything and it is not known to me so that I could serach for the pattern and do a count of that.

What I need to do is find the count of the occurance of each values which are present in the file. The file also has few blank lines.

Thanks,
Rahul

Michael Schulte zur Sur
Honored Contributor
Solution

Re: find the count

Hi,

what about
grep -v "^ *$" file | sort | uniq -c
?

greetings,

Michael
Rahul_13
Advisor

Re: find the count

Hi,

I tried

sed '/^*$/d' < file|sort|uniq -c > newfile

and it worked.

Thanks to everyone.

-Anand.
Michael Schulte zur Sur
Honored Contributor

Re: find the count

Rahul,

no problems and thanks for taking the time to award points!

Michael