Grep Pattern Matching – Show Lines Matching a Pattern and 4 Lines Before Each

awkcommand linegrephp-uxsed

For example, from this file:

CREATE SYNONYM I801XS07 FOR I8010.I801XT07
               *
ERROR at line 1:
ORA-00955: name is already used by an existing object


CREATE SYNONYM I801XS07 FOR I8010.I801XT07
               *
ERROR at line 1:
ORA-00955: name is already used by an existing object



Table altered.


Table altered.


Table altered.


Table altered.


Table altered.


Table altered.


Table altered.


Table altered.

DROP INDEX I8011I01
           *
ERROR at line 1:
ORA-01418: specified index does not exist



Index created.

I want a way to find ORA- and show the ORA- line and the previous 4 lines:

CREATE SYNONYM I801XS07 FOR I8010.I801XT07
               *
ERROR at line 1:
ORA-00955: name is already used by an existing object

CREATE SYNONYM I801XS07 FOR I8010.I801XT07
               *
ERROR at line 1:
ORA-00955: name is already used by an existing object

DROP INDEX I8011I01
           *
ERROR at line 1:
ORA-01418: specified index does not exist

Best Answer

Supposing you're on an elderly system, like HP-UX, that doesn't have GNU utilities, just the old, original BSD or AT&T "grep". You could do something like this:

#!/bin/sh

awk '/ORA-/ { print line1; print line2; print line3; print line4; print $0 }\
// {line1 = line2; line2 = line3; line3 = line4; line4 = $0}' $1

Yes, there's tons of edge conditions this doesn't get right, but whatta ya want for nothing? Also, given that you're working on some decroded, antiquated OS and hardware, you probably don't have the CPU horsepower for fancy error handling.

Related Question