2

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.

4 Answers 4

5

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.

1
  • 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. Commented Mar 21, 2019 at 16:41
2

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.

1

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.

0

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}'

output

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

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.