Wednesday, April 29, 2009

Round off any epoch to day epoch in bash


Whats the present epoch now ?

$ date +%s
1240976848


Which is: GMT: Wed, 29 Apr 2009 03:47:28 GMT

Required: Round off the above epoch value to epoch corresponding to day epoch i.e. epoch corresponding to beginning of the day which is "Wed, 29 Apr 2009 00:00:00 GMT"

Here is the way:

$ echo - | awk '{print int(1240976848/86400)*86400}'
1240963200

Which is "GMT: Wed, 29 Apr 2009 00:00:00 GMT"

Lets have a file like this:

$ cat epochs.txt
a|1240976848|x
b|1240213332|y
c|1240112112|z
d|1240976549|a

Required: Round the 2nd field to the day epoch (beginning of the day epoch)

$ awk 'BEGIN {FS=OFS="|"}
{$2=(int($2/86400)*86400)} {print}
' epochs.txt

output:

a|1240963200|x
b|1240185600|y
c|1240099200|z
d|1240963200|a


** 86400 is the number of seconds in a day. (24*60*60)

Related post:
- Round off functionality using awk in bash
- Round off floats using awk sprintf function

3 comments:

avuton said...

Am I missing something, or why wouldn't the --format argument be used for this?

Jadu Saikia said...

One more way would be:

$ echo 1240976848 - 1240976848 % 86400| bc

1240963200

Jadu Saikia said...

@avuton, thanks for commenting. Do you mean --format of date or something.. please put an example, would be a great help. Thanks.

© Jadu Saikia www.UNIXCL.com