Count number of occurrence of a string in file

if there's a file containing:

money king money queen money cat money also money king

all those strings are on one line in the file.

how can i find out how many times "money king" shows up in the line?

egrep -c "money king" 

wont work.

For this simple sample, try

$ tr " " "\n" <file | awk '/money/{getline; Ar[$1]++}END{for (Ix in Ar) print "money "Ix": "Ar[Ix]}' 
money king: 2
money queen: 1
money also: 1
money cat: 1

Or, for one single line, try

$ awk '{print gsub (srch,srch)}' srch="money king" file
2
1 Like
awk '{n+=gsub("money king", "&")}END{print n}' myFile
2 Likes

Or ,

awk '{s+=gsub(/money king/,"money king") END {print s}}' file

with GNU grep

grep -o "money king" file | wc -l
1 Like
perl -nle '$c+=()=/money king/g;END{print $c}' file

@clx, slight mistake there:

awk '{s+=gsub(/money king/,"money king")} END {print s}' file

2 Likes
#!/bin/bash
#script t2
k=0                               
count=0                           
while read word                   
do                                
if [ "$word" = "$1" ]             
then                              
        k=1                       
else                              
if [ "$word" = "$2" -a $k -eq 1 ] 
then                              
        count=`expr $count + 1`   
        k=0                       
else                              
        k=0                       
fi                                
fi                                
done                              
echo $count      

Run as

tr " " "\n" <mfile|./t2 money king
1 Like
$
$
$ cat f10
money king money queen money cat money also money king
$
$ perl -plne '$_=s/money king//g' f10
2
$
$
1 Like

HI.
Given the augmented data file data1, similar to many of the posted solutions:

money king money queen money cat king king money also money king

the pipeline:

sed 's/money king /&\n/'g data1 |
grep -c 'money king'

produces:

2

For the environment:

OS ker|rel,  machine: Linux, 2.6.26-2-amd64, x86_64
Distribution        : Debian GNU/Linux 5.0.8 (lenny) 
sed GNU sed version 4.1.5
grep GNU grep 2.5.3

See man pages for details.

Best wishes ... cheers, drl

1 Like