Print Line above and line below

Hello evryone,

I am looking for a way to print x line above and x line below ...

The idea is : I've got a little script that I am trying to make it universal to read debug log file.

I search for specific error value ( ERROR, Failed, NOK) and so on..., but most of the time more info can be useful above and below the line printed.

I am lookink for a way, in interative script to select value above and below the line printed but I didn't find any post to help me on this.

Like print 2 lines above and 3 lines below the line printed with the word ERROR for exemple ....

I hope, someone will be able to help me. Please I can only user ksh. I can't use Perl.

Thanks in advanced for your help.

grep -A3 -B2 ERROR file.log
1 Like

If your grep version doesn't support the -A or -B option you could try something like:

awk '/ERROR/{print s RS $0; getline; print; next}{s=$0}' file
1 Like

Thanks Franklin52 for your help.

I think I will go for your code, but I didn't see where I could configure how many lines above and below ?

But I also have trouble as where I work the log file are huge, it's unbelievable ... I need to be able to filter by date, but I can't see where I could add this varibale on your line code ?

Sorry to not be good enough on this ...

Thanks for your help

Maybe some tool designed to log analysis could help your case? Check Download Splunk for free on your operating system

Thanks Bartus11 for your help, as I can't install anything on the server, I can't try your tool.

Anyway, I will try to work on the codes given, and see ....

Thanks.

Here is an example how to print 3 lines above and 4 lines after the pattern:

awk '$0 ~ s {
  for(i=0;i<b;i++){print arr[(NR+i)%b]}
  for(i=0;i<a;i++){print;getline}
  print;exit
}
{arr[NR%b]=$0}
' b=3 a=4 s="ERROR" file

How about plain old ex...this will print 4 lines above/below "ERROR"...

ex -s +'/ERROR/-4,/ERROR/+4 p | q!' file
1 Like