ImranRazaKhan
ImranRazaKhan

Reputation: 2297

grep multiple strings, count lines, echo output for each string

I want to grep multiple patterns from file and then print them with count. My patterns are like

Error code [61440] Error Description 
Error code [61000] Error Description 
Error code [61040] Error Description 

[] contains numbers with variable length and also contain null, i can get count with following command, but to get that i have to see file and check number between [].

cat  mylog.log |   grep  "Error code" | grep 61040 | wc -l

My desired output is like following

Error code [61440] = 90
Error code [61000] = 230
Error code [61040] = 567

Upvotes: 0

Views: 1125

Answers (4)

jkshah
jkshah

Reputation: 11713

Try using awk

awk -F'[][]' '/Error code/ {a[$2]++} END { for (x in a) printf "Error code [%s] = %d\n", x, a[x] }' mylog.log

Output on your sample data

Error code [61440] = 1
Error code [61000] = 1
Error code [61040] = 1

Upvotes: 0

Vijay
Vijay

Reputation: 67319

perl -lne '$x{$1}++ if(/Error code \[([^\]]*)\] Error Description/);
           END{print "$_ => $x{$_}" for(keys %x)}' your_file

Tested:

> cat temp
Error code [61440] Error Description 
Error code [61000] Error Description 
Error code [61040] Error Description 
> perl -lne '$x{$1}++ if(/Error code \[([^\]]*)\] Error Description/);END{print "$_ => $x{$_}" for(keys %x)}' temp
61040 => 1
61000 => 1
61440 => 1
> 

Upvotes: 0

Vasilii Ruzov
Vasilii Ruzov

Reputation: 554

use cat mylog.log | grep "Error code" | sort | uniq -c

Upvotes: 3

user1907906
user1907906

Reputation:

Use sed to extract only the numbers inside [], sort and count these.

$ sed 's/^.*\[\([0-9]*\)\].*$/\1/' < input | sort | uniq -c
1 61000
1 61040
1 61440

Upvotes: 0

Related Questions