-2

How Do i Find Count of a particular word in Different Files in Unix:

I have: 50 file in a Directory (abc.txt, abc.txt.1,abc.txt.2, etc)

What I want: To Find number of instances of word 'Hello' in each file.

What I have used is grep -c Hello abc* | grep -v :0

It gave me result in Form of,

<<File name>>   : <<count>>

I want Output to be in a form

<<Date>>    <<File_Name>>   <<Number of Instances of word Hello in the file>>

1-1-2001     abc.txt              23
1-1-2014     abc.txt.19           57
2-5-2015     abc.txt.49           16
Akshay Sapra
  • 436
  • 5
  • 22

2 Answers2

1

You can use gnu awk >=4.0 (due to ENDFILE) to get the number.
If we know where the data comes from, I will add it.

awk '{for (i=1;i<=NF;i++) if ($i~/Hello/) a++} ENDFILE {print FILENAME,a;a=0}' abc.txt*
Jotne
  • 40,548
  • 12
  • 51
  • 55
1
### Sample code for you to tweak for your needs:
touch test.txt
echo "ravi chandran marappan 30" > test.txt                                                                                                                                     
echo "ramesh kumar marappan 24" >> test.txt
echo "ram lakshman marappan 22" >> test.txt
sed -e 's/ /\n/g' test.txt | sort | uniq | awk '{print "echo """,$1,
"""`grep -wc ",$1," test.txt`"}' | sh

Results:                          
22 -1                                                                                                                                                         
24 -1                                                                                                                                                         
30 -1                                                                                                                                                         
chandran -1                                                                                                                                                   
kumar -1                                                                                                                                                      
lakshman -1                                                                                                                                                   
marappan -3                                                                                                                         
ram -1                                                                                                                            
ramesh -1                                                                                                                       
ravi -1`
ravi
  • 11
  • 2