wrt your problem I have created dummy logs, also note that time is wrt to my timezone. I have also displayed the current time before running the script.
$ cat file2
Mar 9 05:20:01 hostname CROND[PROC_#]: (user) CMD (/path/to/job/)
Mar 9 04:20:01 hostname CROND[PROC_#]: (user) CMD (/path/to/job/)
Mar 9 05:35:01 hostname CROND[PROC_#]: (user) CMD (/path/to/job/)
Mar 5 05:35:01 hostname CROND[PROC_#]: (user) CMD (/path/to/job/)
Mar 9 04:35:01 hostname CROND[PROC_#]: (user) CMD (/path/to/job/)
$ date
Wed Mar 9 05:40:10 IST 2016
$ ./script.bash
Mar 9 05:20:01 hostname CROND[PROC_#]: (user) CMD (/path/to/job/)
Mar 9 05:35:01 hostname CROND[PROC_#]: (user) CMD (/path/to/job/)
$
Contents of script.bash
are as follows:
#!/bin/bash
while read -r line || [[ -n "$line" ]]
do
log_date_str="$(awk '{print $1" "$2" "$3}' <<< "$line")"
log_date="$(date -d "$log_date_str" +%s)"
[[ $(($(date +%s)-$log_date)) -le 3600 ]] && echo "$line"
done < "file2"
we get the date from the log file and convert it into number of seconds elapsed since Unix Epoch and also get that same format for current datetime from command date +%s
Note +%s
is the format here. date -d dateString +%s
can be used to parse a string as date into a desired format.
Once we have both the dates we just subtract it and then find out those results which have difference less than 3600 seconds(1 hour); and then we just print out the log line.
Instead of passing the filename to the while
loop you can pass your ouput of grep