If you don't want to count the number of occurrences, but the number of matching lines, use @heemayl's answer. However, if you want to count each occurrence (so, count word foo word
as 2 hits, not one), you can do:
tail -1000 file | grep -o word | wc -l
The tail
command prints the last 1000 lines, the grep -o word
searches for word
and prints each case found (so it will print it twice if it matches twice) and wc -l
counts the number of lines returned.
Alternatively, you could use something like perl to do the counting:
tail -n 1000 file | perl -alne '$k+=grep{/word/} @F; END{print $k}'
Finally, note that this will also count things like wordsmith
. To match only if your pattern forms an entire word, use grep
with the -w
flag:
tail -1000 file | grep -wo word | wc -l
or
tail -n 1000 file | perl -alne '$k+=grep{/\bword\b/} @F; END{print $k}'