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 #didn't work.

migrated from serverfault.com Mar 21 at 14:56

This question came from our site for system and network administrators.


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.

  • Thanks a lot~~~ – J Wang Mar 14 at 6:50
  • Strictly speaking, this will count the various strings that the patterns matches, not how many times each pattern matches. This makes a difference if the patterns are something other than plain strings. – Kusalananda Mar 21 at 16:41

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.


Using awk:

awk '/aaa/ { count["aaa"]++ }
     /bbb/ { count["bbb"]++ }
     END { for (pat in count) print count[pat], pat }'  file

This would update the count associated with the matching pattern whenever that pattern matches. At the end, a list of counts and the corresponding pattern are outputted.


I Tried with below command

veen:~$ for i in aaa bbb; do perl -pne "s/\n/ /g" i.txt| awk -v i="$i" '{print gsub(i,$0)}';echo $i; done| sed "N;s/\n/ /g"| awk '{print $2,$1}'


veen:~$ for i in aaa bbb; do perl -pne "s/\n/ /g" i.txt| awk -v i="$i" '{print gsub(i,$0)}';echo $i; done| sed "N;s/\n/ /g"| awk '{print $2,$1}'

aaa 1
bbb 2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy