Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
Hi
Can anyone tell me how do i get the number of instances (count) of a word in a file, given that the word can occur multiple times in a line.

I am assuming that your definition of a word is alphanumeric characters surrounded by white space? If so, this korn shell script should work:
#!/bin/ksh wordcnt=0 myword="word" # search for word while read line do cnt=$(printf "%s\n" $line | grep -c ^${myword}$) ((wordcnt+=cnt)) done < datafile echo "Number of $myword words is: $wordcnt"Depending on your unix variant, you may have to use egrep instead of grep.

![]() |
![]() |
![]() |
| Login or Register to Reply | |
| Login | Register |
| Ads by Google |