1

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.

3 Answers 3

1

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$'
2
  • Thanks, but how would I make it so it only does this for the .dat files in the directory?
    – tom
    Commented Feb 8, 2016 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
    Commented Feb 8, 2016 at 10:56
0

Loop over the files:

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

You can also use Perl:

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

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'

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .