Computing.Net > Forums > Unix > number of instances of a word

Computer Problems? Computing.Net has over 1,000,000 posts about all things technology related! Over 90% answered within 24 hours! Click here to start participating now! Also, be sure to check out the New User Guide.

number of instances of a word

Reply to Message Icon

Name: vinay1on1
Date: April 13, 2009 at 04:30:31 Pacific
OS: unix
Subcategory: General
Comment:

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.



Sponsored Link
Ads by Google

Response Number 1
Name: nails
Date: April 13, 2009 at 13:04:49 Pacific
Reply:

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.


0

Response Number 2
Name: ghostdog
Date: April 13, 2009 at 17:59:23 Pacific
Reply:


tr " " "\n" < file | sort | uniq -c

Unix Win32 tools | Gawk for Windows


0

Sponsored Link
Ads by Google
Reply to Message Icon

Related Posts

See More






Use following form to reply to current message:

Login or Register to Reply
LoginRegister


Sponsored links

Ads by Google


Results for: number of instances of a word

Get the last few words of a line? www.computing.net/answers/unix/get-the-last-few-words-of-a-line/7459.html

sh Find the length of a string www.computing.net/answers/unix/sh-find-the-length-of-a-string/7414.html

Terminate paging after x number of msgs www.computing.net/answers/unix/terminate-paging-after-x-number-of-msgs/3400.html