-1

I am writing a shell script program to extract some exceptions from a log file and do some processing. Currently I am using the below command in my script to capture the line nos in the log file that has an exception. The exception lines will contains ERROR keyord just after date and timestamp

lineNos=($(grep -n ERROR $file | grep Exception | cut -d':' -f1 | tail -3))

While testing the current script, I noticed that some log entries contains ERROR and Exceptions in the same row but which is not actually the kind of ERROR that I am looking for(Example line 5) I would like to modify my script in such a way that it will return only the line no 3 in the below example log.

2016-10-21 15:25:37,231 INFO Processinng current row  
2016-10-21 15:25:37,231 INFO com.test.main com.test.controller.CrashException: 
2016-10-21 15:25:37,231 ERROR com.test.main com.test.controller.CrashException: 
2016-10-21 15:25:37,231 DEBUG com.test.main com.test.controller.CrashException: 
2016-10-21 15:25:37,231 DEBUG Processing row with ERROR and Exception 
2016-10-21 15:25:37,231 DEBUG processed row 1: 
0

4 Answers 4

0

If you want to get the lines with the words ERROR and Exception, try:

grep -E "ERROR.*Exception" $file
0

If you use awk in place of grep, you can not only print just the line numbers (more precisely, record numbers) directly, but also test specific whitespace-delimited fields individually e.g.

awk '$3 == "ERROR" && /Exception/ {print NR}' logfile

or (even more specifically - limiting the match of Exception to the final field)

awk '$3 == "ERROR" && $NF ~ /Exception/ {print NR}' logfile
0
cat thelogfile.log | nl -ba | grep "ERROR"

This will pipe the file to nl to number lines, then filter with grep for error lines. if you just want the error line numbers, add awk '{print $1}'. Also cat can line numbers with the -n flag, but i prefer nl.

example for an array variable of line numbers with errors;

linenos=($(cat -n thelogfile.log | grep "ERROR" | awk '{print $1}' | tr "\n" " " | sed 's/$/\n/'))

Edit:

ps the grep can be;

grep ",[0-9]* ERROR"
0

Using more specific regex:

grep '^[0-9, :-]\+ERROR' "$file"

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.