If you don't have access to the GNU utilities version of the date
utility, but you have a recent 1993 version of the Korn shell (such as the one on the last few releases of Mac OS X), you could use:
#!/bin/ksh
# Initialize start date (sd), start time (st), and end date (ed)
# Note that if this script can be run close to midnight, sd and st msut be set
# before ed.
read sd st <<-EOF
$(printf '%(%Y-%b-%d %T)T' '2 hours ago')
EOF
ed=$(date '+%Y-%b-%d')
printf "Start date=%s, Start time=%s, End date=%s\n" $sd $st $ed
awk -v ed=$ed -v sd=$sd -v st=$st '
$1 ~ /^[0-9]{4}-[[:alpha:]]{3}-[0-3][0-9]$/ {
# If the start date matches and the time in this line is later than the
# start time, print this and later lines. If sd and st are late
# yesterday (after 10pm), also print lines from today.
if(($1 == sd && $2 > st) || ($1 == ed && ed != sd))
p = 1
else p = 0
}
p' logfile
If you don't have a recent version of ksh93
for start times shifted a few hours from the current time (like the 2 hours needed for this problem), you can use the POSIX method of specifying the time zone to shift the time, but the value you need to use depend on your current timezone.
For example, I am in the US Pacific timezone which can be specified by setting TZ=PST8PDT
. To shift the output of date to report times 2 hours ago, add two to the number in TZ for your timezone (e.g., TZ=PST10PDT
). To be sure that you have the right value, verify that the command:
TZ=PST10PDT date '+%Y-%b-%d %T\n'
(with your setting for TZ
) prints the date and time two hours ago. Then you can change:
$(printf '%(%Y-%b-%d %T)T\n' '2 hours ago')
in the above script to:
$(TZ=PST10PDT date '+%Y-%b-%d %T')
(with your setting for TZ
) and the script should work with any version of the Korn shell or any other shell (such as bash) that recognizes basic POSIX shell syntax.
If you want to try this on a Solaris/SunOS system, also change awk
to /usr/xpg4/bin/awk
or /usr/xpg6/bin/awk
.