1) "date" is not a command inside the nawk program. I used it as a variable, and I set it to "" at the beginning to make sure it is empty at the start. I also used it as a flag (like I used "rightday" in the first). This is poor programming practice, but I learned to program in the old days when space was valuable, and still use the old tricks without thinking. (Try writing a good program when the operating system, program, data, and "working" space must all fit in 16K of memory!)
2) You said you wanted only errors from yesterday. If the program finds today's date, then it has found all errors from yesterday, so it stops looking and exits.
Without this line, the program will print errors from today, but still give yesterday's date: on the file
Mon Sep 30 02:09:33
ORA012:error 12345 in xxjob...
ORA014:normal 23455.....
Tue Oct 1 03:29:43
ORA012:normal 23456....
ORA014:error 34512 in xxjob...
the program would give
Mon Sep 30 02:09:33
ORA012:error 12345 in xxjob...
Mon Sep 30 02:09:33
ORA014:error 34512 in xxjob...
which is wrong! (Your program would do the same except it will not print the second date.) The {exit} line causes the program to stop as soon as it finds Tue Oct 1, so it gives
Mon Sep 30 02:09:33
ORA012:error 12345 in xxjob...
I am assuming your log is ordered by date, so that stuff for today will only occur after all stuff from yesterday.
3)"yesterday" means only the day before today, not earlier days. The program compares dates against yesterday's date. It will not print anything until it finds yesterday's date. Then it saves the line with the date and looks for lines with ":error". When it finds one, it will print the line with the date that it saved, and then the line with the error. If it finds another line with yesterday's date, it will save that line in place of the first, and print it when it finds an error. It does not print a date for anything other than error lines, and only when the date of the error is yesterday. When it finds today's date, it knows it has found everything from yesterday, so it quits.
Try this rewrite. I have changed the variable names to clear up the confusion, and added a separate flag for the date check. Also, the double quotes around the shell variables will prevent a format error that occurs for dates between 0 and 9 (such as today's date!):
Code:
#!/bin/csh -f
set yestermonth=`env TZ="$TZ+24" date +%b` #=month for yesterday
set yesterday=`env TZ="$TZ+24" date +%e` #=day number for yesterday
set tomonth=`date +%b` #=month for today
set today=`date +%e` #=day number for today
nawk '
BEGIN {rightday=0; dateline=""} # initialize variables
# if date = yesterday, set flag, save date
$2 == '"$yestermonth"' && $3 == '"$yesterday"' {rightday=1; dateline=$0}
# if date = today, we are done: exit.
$2 == '"$tomonth"' && $3 == '"$today"' {exit}
# if error yesterday, print date, print error line
rightday == 1 && /:error/ {print dateline; print}
' alert_mes.log