Marshall Marshall - 1 month ago 11
Python Question

sed conditional merge NEXT line

I have a log like below

10-26-2016 10:00:00 INFO bla bla bla
10-26-2016 10:00:00 ERROR This is the error
error line 2
error line 3
error line 4
10-26-2016 10:00:00 INFO bla bla bla2


I need a sed or a python command to get the error line below

==========================
his is the error
error line 2
error line 3
error line 4
==========================


This is a huge file and I cant open the file. Kindly assist. Thanks

Answer

With GNU sed:

sed 's/^[0-9]/\n&/' file | sed -n '/ ERROR/,/^$/{s/^[0-9].* ERROR \(.*\)/\1/;/^$/d;p}'

Output:

This is the error
error line 2
error line 3
error line 4

How it works:

The first sed command (sed 's/^[0-9]/\n&/' file) inserts a blank line before every line which starts with a digit.

Output:


10-26-2016 10:00:00 INFO bla bla bla

10-26-2016 10:00:00 ERROR This is the error
error line 2
error line 3
error line 4

10-26-2016 10:00:00 INFO bla bla bla2

Second sed commnad prints only blocks which start with a line which contains ERROR and ends with a blank line. The part in curly brackets removes here 10-26-2016 10:00:00 ERROR in this block and deletes the trailing blank line (/^$/d) in this block.

Comments