3

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
Dave
  • 367
  • 2
  • 5
  • 11
  • 1
    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
  • 3
    Because there may be a better way – Dave Feb 19 '13 at 13:08
  • 7
    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 – serverhorror Feb 19 '13 at 13:17
  • Then you could instead ask for alternate ways. Also Server Horror's comment should be an answer. – Alex Hall Dec 14 '17 at 00:05

3 Answers3

6
cat | grep ^foo | wc -l

TO show how many lines containing foo are there.

MadHatter
  • 79,770
  • 20
  • 184
  • 232
Soham Chakraborty
  • 3,584
  • 17
  • 24
3

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.)

Brigo
  • 1,534
  • 11
  • 8
3

Per Server Horror's comment:

grep -c pattern file

Alex Hall
  • 131
  • 3