Languages and Scripting

# find the count

SOLVED
Go to solution

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

Thanks,
Rahul
11 REPLIES 11
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 ?
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.
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."
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
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

## 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

Honored Contributor
Solution

## Re: find the count

Hi,

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

greetings,

Michael

## Re: find the count

Hi,

I tried

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

and it worked.

Thanks to everyone.

-Anand.
Honored Contributor

## Re: find the count

Rahul,

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

Michael