The UNIX and Linux Forums

The UNIX and Linux Forums (http://www.unix.com/index.php)
-   Shell Programming and Scripting (http://www.unix.com/shell-programming-and-scripting/)
-   -   Count the number of occurence of perticular word from file (http://www.unix.com/shell-programming-and-scripting/38139-count-number-occurence-perticular-word-file.html)

rinku 05-25-2007 07:25 AM

Count the number of occurence of perticular word from file
 
I want to count the number of occurence of perticular word from one text file.

Please tell me "less" command is work in ksh or not. If it is not working then instead of that which command will work. :confused:

blowtorch 05-25-2007 07:36 AM

The 'less' command is used to view a file. Use grep to search for a particular word in a file. You can use this to count the number of occurrences too, just check the man page for the exact switch.

funksen 05-25-2007 09:36 AM

grep -o <string> <file> | wc -w

cfajohnson 05-25-2007 09:04 PM

Quote:

Originally Posted by rinku
I want to count the number of occurence of perticular word from one text file.


Code:

tr -cs 'A-Za-z' '\n' < FILE | grep -c "WORD"

pelipeplips 08-08-2007 05:20 AM

Quote:

grep -o <string> <file> | wc -w
I tried using grep with the "-o" option and it gives me this error:
grep: illegal option -- o
What does "-o" option do?

I also need to find an occurence of a certain string within a file. Currently I'm using:
Code:

grep -c 'abc' sample.txt
But the code above only counts the occurrences per line. How will i get the total count of the 'abc' words regardless of how many occerence they have per line?

Example:
This is line 1 abc and abc
This is line 2 abc


Klashxx 08-08-2007 06:53 AM

Use:
Code:

awk '{
    for (i=1;i<=NF;i++)
        if ( $i == "abc")
        c++
    }
END{
print c}' sample.txt

Or:
Code:

awk '
BEGIN {
RS=FS
}
{
if ( $0 ~ /abc/ )
  c++
}
END{
print c++
}' lsample.txt


Shell_Life 08-08-2007 11:09 AM

Quote:

Originally Posted by cfajohnson (Post 302118990)

Code:

tr -cs 'A-Za-z' '\n' < FILE | grep -c "WORD"

This solution does not work.

Here is a sample file:
Code:

a aa aaa
aaa aa a
aaa aa a aaa aa a aaa

Here is one test:
Code:

tr -cs 'A-Za-z' '\n' < FILE | grep -c "aaa"
It gives the total of words as '3', when the answer is '5'.

Here is another possible solution for those who want to use shell script:
Code:

#!/bin/ksh
typeset -i mCnt=0
mWord='aaa'
for mEach in `cat input_file`
do
  if [ "${mEach}" = "${mWord}" ]; then
    mCnt=${mCnt}+1
  fi
done
echo 'Total words for '${mWord}' = '${mCnt}



All times are GMT -4. The time now is 01:35 PM.

Linux and Unix Supported by: vBulletin
Search Engine Optimisation provided by DragonByte SEO v1.0.9 (Pro) - vBulletin Mods & Addons Copyright © 2014 DragonByte Technologies Ltd.
The UNIX and Linux Forums Content Copyright ©1993-2013. All Rights Reserved.
Forum Operations by The UNIX and Linux Forums