Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

How can I count the number of lines matching a pattern returned from a linux command

I want the number of lines returned beginning with 'foo' , so if I pipe the output to grep will this work?

cat | grep -c ^foo
share|improve this question
Why do you even ask, if you answered the question by yourself. Or simply check with your next nearest shell. – Roman Feb 19 '13 at 12:36
Because there may be a better way – Dave Feb 19 '13 at 13:08
Useless use of cat. grep -c pattern file. Yes it's not that much but as soon as you run that thru a loop that runs a couple of thousand times you'll want to save on forks – Server Horror Feb 19 '13 at 13:17

From grep man page:

*General Output Control*

    -c, --count      Suppress normal output;

instead print a count of matching lines for each input file. With the -v, --invert-match option (see below), count non-matching lines. (-c is specified by POSIX.)

share|improve this answer
cat | grep ^foo | wc -l

TO show how many lines containing foo are there.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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