I am working on a script which will show all the results and their count on the console based on a particular string .

Example: Suppose I searched for a string called "ERROR", I got the below results, here number of ERROR occurrence is 5.

2013-12-08 13:43:07 SUSE::SRPrivate - [error]  ERROR: Couldn't connect to server: (7)
2014-01-08 13:43:06 SUSE::SRPrivate - [error]  ERROR: Couldn't connect to server: (7)
2014-02-08 13:43:24 SUSE::SRPrivate - [error]  ERROR: Timeout was reached: (28)
2014-03-08 13:43:03 SUSE::SRPrivate - [error]  ERROR: Couldn't connect to server: (7)
2014-04-08 13:43:24 SUSE::SRPrivate - [error]  ERROR: Timeout was reached: (28)

I want to show both logs and number of occurrences(lines). I wrote this below script to show the logs:

(zgrep -E "ERROR|Exception" $SS_HOME/logs/*.gz $PROBE_HOME/logs/*.gz $RELAY_HOME/logs/*.gz ;find . -type f -name "*.log" -exec cat {} +) | grep -F ERROR | sort

I don't know how to add the count the lines. Please let me know for any additional information.


To show matching lines, count them, and show the count, with awk:

awk '/ERROR/{err++; print} END{print "errors:", err}'

To summarize errors and exceptions:

awk '/ERROR/||/Exception/{faults++; print} END{print "faults:", faults}'

To count errors and exceptions separately:

awk '/ERROR/{err++; print} /Exception/{exc++; print}
     END{print "errors:", err, "exceptions:", exc}'

Note: The awk programs work as filter, they read from standard input and write to standard output, but you can also provide the data files as arguments. So to use is (as asked in the comment below) with one or more log-files use awk '...' *.log, or if you want one or more gz-files uncompressed before parsing them with awk use, e.g., zcat *.gz | awk '...' (where you substitute any of the above awk programs for awk '...').

  • Hi Janis , thank you for the reply . if i want to search in .gz and .log file then how do i modify the command . – user112232 May 25 '15 at 5:51
  • @user112232; I've added a note. – Janis May 25 '15 at 9:05

Just use wc command with the -l option:

wc -l

If you wish to print the logs as well, then you can use tee:

cat logs.txt | grep -i error | tee >(wc -l)
  • if i am using this command , i can only see the number of counts but i want to show the logs also . – user112232 May 18 '15 at 6:19
  • Answer has been updated as per your requirements. – shivams May 18 '15 at 6:29

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.