2

I've search the web for this but couldn't find the solution I wanted.

I used grep to search for lines having the word one and that works fine.

I want grep to also count the matched lines as well. But I only get the number only.

I tried this but no cigar.

grep -cn 'one' foo 
2

Option c is to count and option n is to show lines. But it still shows the count only.

Thus far, this is the only way to do it. Running grep twice :(

grep  'one' foo ; grep  'one' foo  | wc -l
one two three
seven one blah
2

Is it possible for grep to show both the matches and the count without repeating the command again?

BTW, I know awk can do this as I've seen in my research. But I want to know if grep can do this. Thanks in advance :)

noob2021
  • 23
  • 3
  • `grep 'one' foo | tee >(wc -l) ` or `grep 'one' foo | tee /dev/tty | wc -l` would work https://stackoverflow.com/questions/670784/redirecting-bash-stdout-stderr-to-two-places and https://superuser.com/questions/7448/can-the-output-of-one-command-be-piped-to-two-other-commands – Jerry Jeremiah Aug 24 '21 at 22:29
  • 2
    Possible duplicate: https://stackoverflow.com/questions/670784/redirecting-bash-stdout-stderr-to-two-places – Jerry Jeremiah Aug 24 '21 at 22:31
  • WOW! It works!!! Thanks Jerry Jeremiah!!! You're awesome!!! – noob2021 Aug 24 '21 at 22:58
  • @noob2021 you know that's not `grep` outputing the count, right? The answer to your question of "Can grep show count and matches at the same time?" is simply `no`. – Ed Morton Sep 01 '21 at 21:36

0 Answers0