Home > Net >  How to count the number of occurences of a word in several files?
How to count the number of occurences of a word in several files?

Time:09-11

I have a directory containing a lot of files.

I would like to display with one shell command the list of all the xml files in the directory with the number of times a specific word appears in each file.

Like this :

file1.xml 333
file2.xml 525
...
file67.xml 767

I first devised the command to obtain the number of occurances for only one file :

grep -w WORD FILE.XML | wc -l

But I hit a snag when I try to use it to do the same thing with all the xml files in one directory.

I tried this command :

find . -name "*.xml" -exec grep -w WORD {} | wc -l  

and I really thought it would work because I already used several times find in this context but it didn't. Here is the error output :

wc:  : Aucun fichier ou dossier de ce type
find: missing argument to `-exec'

Anyone knows how I can make this command right please ?

CodePudding user response:

grep has a built-in -c option that returns the number of matches. So you don't need to pipe to wc -l.

find . -name '*.xml' -exec grep -H -c -w WORD {}  

The -H option ensures that it includes filenames in the output even if there's only one matching file. By default, grep only shows filenames in the output when it has more than one filename argument.

  • Related