Minues four hours from time

Hi,

I am trying to design a script, which will monitor a log file, and it should dump all the rows that were logged between now and past four hours.

The date format within the logs is "2/Jan/2011:03:13:27". So I am using below command to substract four hours from the current time :

$ date +%d/%b/%Y:%H| awk -F":" '{ print $1 ":" ($2-4)}'
13/Jan/2011:8

It gives me "13/Jan/2011:8" , whereas i need it to be "13/Jan/2011:08".

Please let us know how can i accomplish this.

I did look within this link : http://www.unix.com/answers-frequently-asked-questions/13785-yesterdays-date-date-arithmetic.html, but couldn't find a suitable answer.

TIA - John

date '+%d/%b/%Y:%H' | awk -F: '{printf("%s:%02d\n",$1,$2-4)}'

Anurag, I'm getting this output.

5$ date '+%d/%b/%Y:%H' | awk -F: '{printf("$s:%02d\n",$1,$2-4)}'
$s:00

Should be %s, not $s
Corrected in earlier post.

Thank You, it is working.

$s:%02d\n

Could you please illustrate why does this mean, so that i can utilize later on for other purpose.?

printf("%s:%02d\n",$1,$2-4)

1st argument to printf is the format. %s to print $1 as string, %d is to print as integer where 02 is to padd ZERO on left if ($2-4) width is less than 2.
For more detail, Look at printf manual or other info available on internet.

1 Like

Thanks a lot !

Not worried about the case of running this script before 4am?

1 Like

Thanks Chubler_XL. It should be:

date '+%d/%b/%Y:%H' | awk -F: '{printf("%s:%02d\n",$1,$2>=4?$2-4:24-(4-$2))}'