Reputation: 32286
The date command returns the current date. I want the nearest 5 minute interval. For e.g.
# date
Thu Mar 15 16:06:42 IST 2012
In this case I want to return ...
Mar 15 16:05:00
Is it possible in the shell script? or is there any one liner for this?
Update:
the date is in this format...
2012-03-10 12:59:59
Latest update:
The following command works as expected. Thanks for the response.
head r_SERVER_2012-03-10-12-55-00 | awk -F'^' '{print $7}' | awk '{split($2, a, ":"); printf "%s %s:%02d:00\n", $1, a[1],int(a[2]/5)*5}'
Correct result:
2012-03-10 12:55:00
But I want to show other fields as well other than date. The following does not work:
head r_SERVER_2012-03-10-12-55-00 | awk -F'^' '{print $1, $2, $7, $8}' | awk '{split($2, a, ":"); printf "%s %s:%02d:00\n", $1, a[1],int(a[2]/5)*5}'
Wrong result:
565 14718:00:00
It should be ...
565 123 2012-03-10 12:55:00 country
Upvotes: 0
Views: 3194
Reputation: 46876
If you have GNU AWK available, you could use this:
| gawk '{t=mktime(gensub(/[-:]/," ","g")); print strftime("%Y-%m-%d %H:%M:%S",int(t/5)*5);}'
This uses the int()
function, which truncates, which sort of means "round down". If you decide you'd prefer to "round" (i.e. go to the "nearest" 5 second increment), replace int(t/5)
with int((t+2.5)/5)
.
Of course, if you're feeling masochistic, you can do this in pure shell. This one only truncates rather than rounding up.
[ghoti@pc ~]$ fmt="%Y-%m-%d %H:%M:%S"
[ghoti@pc ~]$ date "+$fmt"
2012-03-15 07:53:37
[ghoti@pc ~]$ date "+$fmt" | while read date; do stamp="`date -jf \"$fmt\" \"$date\" '+%s'`"; date -r `dc -e "$stamp 5/ 5* p"` "+$fmt"; done
2012-03-15 07:53:35
Note that I'm using FreeBSD. If you're using Linux, then you might need to use different options for the date
command (in particular, the -r and -f options I think). I'm runninB this in bash, but it should work in pure Bourne shell if that's what you need.
Upvotes: 1
Reputation: 247072
$ date="2012-03-10 12:59:59"
$ read d h m s < <(IFS=:; echo $date)
$ printf -v var "%s %s:%d:00" $d $h $(( m-(m%5) ))
$ echo "$var"
2012-03-10 12:55:00
I use process substitution in the read command to isolate changes to IFS in a subshell. `
Upvotes: 2
Reputation: 4224
date | awk '{split($4, a, ":"); printf "%s %s %s:%02d:00", $2, $3, a[1],int(a[2]/5)*5}'
Upvotes: 2