Skip to main content

how to grep with multiple filters and print one by one [Resolved]

I need count some patterns in logs, I can use

grep aaa ./logs | wc -l

grep bbb ./logs | wc -l

is there a easy way to do all things in one line? like

cat ./logs | grep -c aaa | grep -c bbb (can't work).

thanks~


Question Credit: J Wang
Question Reference
Asked March 15, 2019
Tags: linux
Posted Under: Network
7 views
2 Answers

You can use the following command:

$ grep -oh -e aaa -e bbb ./logs | sort | uniq -c

From man grep, you can read:

-o, --only-matching Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line.

Also, for -h:

-h, --no-filename Suppress the prefixing of file names on output. This is the default when there is only one file (or only standard input) to search.

The -e is used to match either one. Then, the results are sorted and counted using uniq.


credit: Khaled
Answered March 15, 2019

You can use the -e PATTERN flag. In order to count how many lines contain either or both aaa or bbb:

grep -e aaa -e bbb ./logs | wc -l

If you want to count aaa and bbb separately, check the solution by Khaled.


credit: jornane
Answered March 15, 2019
Your Answer