Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Find number of occurences of a string/character in a file 1

Status
Not open for further replies.

bansalhimanshu

Programmer
Sep 27, 2004
36
0
0
US
I need to find the count of a character or a set of characters in a file. Is there a unix command for that?

Like for given file I need to find out number of occurences of "af":
afbcd efg abef akljklj jklj ljlj
ljlkj jflja fjklja j ljkfaj jkj
jljaf jflaj jafj;ajj;jj jlkj;

 
Here's one way:

[tt]awk -F af '{tot+=NF-1}END{print tot}' input[/tt]

Annihilannic.
 
Thanks Annihilannic, it was very really good. This script although does not work for searching for count of word. Can you write similar script for a word as well.

Are you aware if there is any unix inbuild command for this purpose.
 
In a ksh-like shell:
w="word"; f=/path/to/input
echo $w appears $(($(cat $f | wc -w)-$(sed "s!$w!!g" $f | wc -w))) times in $f


Hope This Helps, PH.
Want to get great answers to your Tek-Tips questions? Have a look at FAQ219-2884 or FAQ181-2886
 
bansalhimanshu said:
This script although does not work for searching for count of word.

What do you mean? Can you give an example?

If you only want to match whole words (i.e. "af" is counted, but "after" is not, for example) then PHV's solution is better.

I get a result of '3' for the sample data you provided, which looks correct to me.

Annihilannic.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top