2

Just getting the hang of Linux Command Line, but having trouble with grep commands.

I'm trying to find out how many times a word appears in the last 1000 lines of a text file

I have a feeling that I need to use grep and pipes but can't figure it out

2 Answers 2

6

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}'
2
  • Thank you everyone! I think this one works the best for what I want to achieve "tail -1000 file | grep -wo word | wc -l" as this counts the specific word and not other words it could be in. I believe this also achieves the same result? "tail -1000 file | grep -wc word"
    – 6rxobrut
    Mar 18, 2015 at 12:49
  • 2
    @6rxobrut no, tail -1000 file | grep -wc word will count word word as one, not two. The -c option counts matching lines not occurrences.
    – terdon
    Mar 18, 2015 at 12:50
2

Here is a general pattern:

tail -1000 file.txt | grep -c "word"

This will print the number of lines that contain the pattern "word" in the last 1000 lines of the file named file.txt. Here we have used tail -1000 to get the last 1000 lines of the file and then just used grep -c to count for the occurrences of the pattern in those lines.

0

You must log in to answer this question.

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