Display specific lines content from the file

Hell,

I want to grep certain word from file and display above 2 lines and after two lines.

Here is the content of sample file.

Mar 14, 2013 12:56:59 AM Agent.Agent SendTo
INFO: Connection to server:7041 - Credential Transmit Successesful
Mar 14, 2013 8:54:21 AM cgent SendTo
WARNING: Data Transmit to Server Failed - Broken pipe
Mar 14, 2013 9:54:01 AM cAgent SendTo
INFO: Connection to server:7041 - Connect Successesful
Mar 14, 2013 10:56:59 AM Agent SendTo

I wanted to grep the word "WARNING" and I want +2 and -2 lines of the grep word("WARNING") along with the grep word line.

Output should be:

INFO: Connection to server:7041 - Credential Transmit Successesful
Mar 14, 2013 8:54:21 AM cgent SendTo
WARNING: Data Transmit to Server Failed - Broken pipe
Mar 14, 2013 9:54:01 AM cAgent SendTo
INFO: Connection to server:7041 - Connect Successesful

I Tried grep -A -B command but am getting the below error.

$ grep -B 2 "WARNING"  sampleFile
grep: illegal option -- B
Usage: grep -hblcnsviw pattern file . . .

Hope the below link helps you

Hi, try this: warning, the sampleFile is present two times in this script

awk '/WARNING/{
printf "awk %cNR>=%d && NR<=%d%c sampleFile\n",39,NR-2,NR+2,39; 
}' sampleFile | sh

Interesting method, but this will be extremely slow on even medium sized files since it must reread the entire file for each separate event...

It's possible to use an array in awk to save lines for later and print them at need.

$ cat warnlog.awk

BEGIN { CONTEXT=2 }

# Recall N lines ago up to 9 lines
function last(N)
{
        if(N>L) return("");
        return(LINE[(L-N)%10]);
}

{ LINE[(++L)%10]=$0 } # Remember line for later

$0 ~ REGEX  {
        for(N=CONTEXT; N>=0; N--) print last(N);
        for(N=0; N<CONTEXT; N++) { getline ; print }
}

$ awk -f warnlog.awk REGEX="WARNING" inputfile

INFO: Connection to server:7041 - Credential Transmit Successesful
Mar 14, 2013 8:54:21 AM cgent SendTo
WARNING: Data Transmit to Server Failed - Broken pipe
Mar 14, 2013 9:54:01 AM cAgent SendTo
INFO: Connection to server:7041 - Connect Successesful

$

You can override the value of CONTEXT too if you want more lines. Use nawk on solaris.

Can you get a better version of grep? Beyond this problem, it will save you much future time. Your version is missing a lot of useful options.

$ uname
Linux
$ grep -C 2 WARNING temp.x
INFO: Connection to server:7041 - Credential Transmit Successesful
Mar 14, 2013 8:54:21 AM cgent SendTo
WARNING: Data Transmit to Server Failed - Broken pipe
Mar 14, 2013 9:54:01 AM cAgent SendTo
INFO: Connection to server:7041 - Connect Successesful

You must tell which version you are using and let's check if your OS supports grep -A and grep -B supports.

He got an error when he tried grep -B option.

Another awk

awk '{c=b;b=a;a=$0} /WARNING/ {print c"\n"b"\n"a;getline;print;getline;print}'