AIX: using grep command to log two lines from a file AIX: using grep command to log two lines from a file shell shell

AIX: using grep command to log two lines from a file


Given the sample input you posted, all you need is:

$ awk -v RS= -F'\n' '/USR02|USH02|TCURR|REGUH|LFB1|LFA1/ {print FILENAME, $1, $3}' filefile Tue Jul  2 08:42:16 2013 +02:00 ACTION :[68] 'update SAPPRD.USR02 set uflag=64 where BNAME='CANAS' and MANDT='000''

If that doesn't do it, post some more representative input and expected output.

Explanation as requested below by fedorqui

  • RS= => records are separated by blank lines
  • -F'\n' => fields within a record are separated by newlines
  • /USR02|USH02|TCURR|REGUH|LFB1|LFA1/ => look for records thatcontain any of the |-separated strings
  • print FILENAME, $1, $3 => print the name of the current file, and the 1st and 3rd lines/fields of the current record, the 1st line being the date and the 3rd being the ACTION.


Ed Morton gave an awk solution with setting RS and FS.Here is another solution with awk:

awk '!$0{delete a;next}{a[NR]=$0}/USR02|USH02|TCURR|REGUH|LFB1|LFA1/{print a[NR-2];print $0}' file

the first part !$0{delete a;next} could be removed if your file is not a huge monster:

awk '{a[NR]=$0}/USR02|USH02|TCURR|REGUH|LFB1|LFA1/{print a[NR-2];print $0}' file

output with your input:

kent$  awk '{a[NR]=$0}/USR02|USH02|TCURR|REGUH|LFB1|LFA1/{print a[NR-2];print $0}' f                                                                                        Tue Jul  2 08:42:16 2013 +02:00ACTION :[68] 'update SAPPRD.USR02 set uflag=64 where BNAME='CANAS' and MANDT='000''


Why don't you do it like this?

grep -Ei "USR02|USH02|TCURR|REGUH|LFB1|LFA1" -B 2 file

grep -e admits multiple parameters. So instead of grep -i ONE and then grep -i TWO, you can do grep -Ei "ONE|TWO".

With -B 2 what you do is to print the two previous lines of the matched line.

Test

All together will make the following:

$ grep -Ei "USR02|USH02|TCURR|REGUH|LFB1|LFA1" -B 2 fileTue Jul  2 08:42:16 2013 +02:00LENGTH : '222'ACTION :[68] 'update SAPPRD.USR02 set uflag=64 where BNAME='CANAS' and MANDT='000''

and if you do not want the line in the middle,

$ grep -Ei "USR02|USH02|TCURR|REGUH|LFB1|LFA1" -B 2 file | grep -v LENGTHTue Jul  2 08:42:16 2013 +02:00ACTION :[68] 'update SAPPRD.USR02 set uflag=64 where BNAME='CANAS' and MANDT='000'