Grepping before and after lines for required string

Hi All,

I am new to AIX unix . i need to grep for a pattern and if pattern is found then i need 3 before the pattern line found and 3 lines after the pattern found.

grep greps lines, it can't do logic or other recall, it's not really a programming language. The awk language can do logic and recall.

$ cat <<"EOF" > context.awk
# 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 ~ PATTERN { for(N=3; N>=1; N--) print last(N);
        print;
        for(N=0; N<3; N++) { getline ; print }
}
EOF

$ nawk -f context.awk PATTERN="myregex" filename1 filename2 ...

Hi I have to search this in *.gz file , will it be work?

---------- Post updated at 03:16 PM ---------- Previous update was at 03:14 PM ----------

like in GNU unix we have grep -a and grep -b similar to that . will your solution works for .gz files also

GNU unix is a contradiction in terms. GNU means "GNU's not UNIX". :slight_smile:

Nope. Neither will grep. You can still stream it, of course.

gunzip < filename | nawk -f context.awk PATTERN="myregex"

Slightly improved version:

cat <<"EOF" > context.awk
# Recall N lines ago up to 9 lines
function last(N)
{
        if(N>L) return("");
        return(LINE[(L-N)%CTX]);
}
 
{ LINE[(++L)%10]=$0 } # Remember line for later
 
$0 ~ PATTERN { for(N=CTX; N>=1; N--) print last(N);
        print;
        for(N=0; N<CTX; N++) { getline ; print }
}
EOF
$ gunzip < filename | awk -f context.awk CTX=3 PATTERN="myregex"

Thanks a lot this what i need , one more question if i give *.gz to found the pattern in multipile gz file it's not working any idea about that

If you have zcat, you can do zcat *.gz | nawk ...

If you don't, you can do for FILE in *.gz ; do gunzip < "$FILE" ; done | nawk ...

For example in my directory i have
1.gz
2.gz
3.gz
4.gz

and all of them contains log and i want search the samething in all the gz files

zcat *.gz | nawk -f context.awk PATTERN="myregex"

Hi I ran the command and got the follwoing output

1.gz.Z: A file or directory in the path name does not exist.
2.gz.Z: A file or directory in the path name does not exist.
3.gz.Z: A file or directory in the path name does not exist.

Your version of zcat expects .Z files for some reason.

Use my other version.

for FILE in *.gz ; do gunzip < "$FILE" ; done | nawk ...

Thank you very much that's amazing working perfectly!!!:slight_smile:

1 Like