Friday, January 25, 2008

Like grep, but not

This code is like using grep. However, grep only returns the lines that contain the actual text you are searching for. This code allows you to return x number of lines before and after the text you are searching for along with the line itself. This command came in handy searching for information in the uds log files.

nawk 'c-->0;$0~s{if(b)for(c=b+1;c>1;c--)print r[(NR-c+1)%b];print;c=a}b{r[NR%b]=$0}' b=2 a=4 s="fetchHotel" file

b is the number of lines to print before the line encountered and a is the number of lines to print after the line is encountered.

s=”string” string you are looking for (in this case fetchHotel)
and file is the file you are looking in.

By Kris Chappell