This is what I currently have, however it prints the total number of times Author appears in all of the files: 128367

grep -roh 'Author' $1 | wc -w

However how do I print out the word count for each file separately?

Also the argument it's taking is a folder with the files in.


You just could use grep to do this. The second grep is to filter files with no matches.

grep -rc 'Author' ${1} | grep -v ':0$'
  • Thanks, but how would I make it so it only does this for the .dat files in the directory? – tom Feb 8 '16 at 9:10
  • If there are no subdirectories to search you could use grep -c 'Author' ${1}/*.dat where ${1} is a directory. Otherwise you have to iterate over the files like mentioned by choroba. – Thomas Feb 8 '16 at 10:56

Loop over the files:

for file in "$1"/* ; do
    if [[ -f "$file ]] ; then
        printf %s: "$file"
        grep -o Author "$file" | wc -w

You can also use Perl:

perl -lne 'BEGIN { $c = 0 }
           $c++ while /Author/g;
           if (eof) { print "$ARGV: $c"; $c=0 }
          ' "$1"/*

With GNU Parallel:

parallel --tag 'grep -oh Author {} | wc -w' ::: *.dat

If there are subdirs:

find . -name '*.dat' | parallel --tag 'grep -oh Author {} | wc -w'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.