Cesar
Cesar

Reputation: 4116

Summarize count of multiple patterns in shell

I have a log file and the following commands

grep '"REFERENCE":"78","STATUS":"Buffered"' file.log | wc -l
grep '"REFERENCE":"78","STATUS":"Delivered"' file.log | wc -l
grep '"REFERENCE":"78","STATUS":"Not Delivered"' file.log | wc -l

Is there a way using a one liner to get an output like:

Buffered: 30
Delivered: 1200
Not Delivered: 589

The output has not to be exactly the same.

Upvotes: 0

Views: 78

Answers (3)

chepner
chepner

Reputation: 531135

Use awk to extract the desired lines and output only the status, then use sort and uniq to obtain the counts for each unique status:

awk -F, '/"REFERENCE":"78"/ { print $2 }' | sort | uniq -c

This answer may need to be adjusted, depending on the exact format of you input lines. I assume for now that the second field in a comma-delimited line is "STATUS":"<status>".

Upvotes: 0

Cesar
Cesar

Reputation: 4116

I just find a solution to my problem, borrowed from here

grep -oP '"REFERENCE":"79","STATUS":".*?"' file.log | sort | uniq -c

Example output:

15605 "REFERENCE":"79","STATUS":"Buffered"
24280 "REFERENCE":"79","STATUS":"Delivered"
10224 "REFERENCE":"79","STATUS":"Not Delivered"

Upvotes: 1

Piotr Wadas
Piotr Wadas

Reputation: 1884

Sure, instead of counting lines consider -c switch for grep - it returns number of matches found, and $() or SINGLEQUOTEcommandSINGLEQUOTE syntax in bash, then combine it with bash simple arithmetics $(($X+$Y)) into one command, similarly to:

OUTCOUNT=$((`grep -c aaa file1.txt` + `grep -c bbb file2.txt` + `grep -c ccc file3.txt`))

Upvotes: 0

Related Questions