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