Count search results on Linux shell

Lets imagine you want to search for a term in a file and you want to know, how often it can be found in the file. With this command combination you can count search results on bash:

$> less xmlfile.xml | grep SearchmeIfYouCan | wc -l

This is how this way to count search results works:

The input file is opened in less. Afterwards the output of less is piped to grep, that searches withing the output for the given string “SearchmeIfYouCan”.
Usually the output – the lines of findings – would now be printed to screen. But we use another pipe to send these lines to the wc command.
The wc command, in combination with it’s -l (or –lines) parameter, counts the number of given newlines inside the given output.
Hence every finding found by grep is normally printed in a single line, the number of newlines detected by wc is the count of findings in the given file.

Btw.: With wc you can also easily count the words in a file or determine the byte count of a file. See http://linux.die.net/man/1/wc for further information.

1 thoughts on “Count search results on Linux shell

Leave a Reply

Your email address will not be published. Required fields are marked *

 

This site uses Akismet to reduce spam. Learn how your comment data is processed.