Saturday, January 10, 2009

Convert seconds to hour minute seconds format - bash and awk


Lets see how using bash printf command we can format seconds to h:m:s format.

The bash script "convert.sh"


#!/bin/sh
#Convert seconds to h:m:s format

[ -z ${1} ] && echo "Usage: $(basename $0) <seconds>" && exit||secs=${1}
_hms()
{
local S=${1}
((h=S/3600))
((m=S%3600/60))
((s=S%60))
printf "%dh:%dm:%ds\n" $h $m $s
}

_hms ${secs}


Executing:

$ ./convert.sh
Usage: convert.sh <seconds>

$ ./convert.sh 456
0h:7m:36s

The bash one liner for the above script will be:

$ secs=456
$ printf ""%dh:%dm:%ds"\n" $(($secs/3600)) $(($secs%3600/60)) $(($secs%60))

0h:7m:36s

The awk one liner for this:

$ echo - | awk -v "S=456" '{printf "%dh:%dm:%ds",S/(60*60),S%(60*60)/60,S%60}'

0h:7m:36s

6 comments:

Jadu Saikia said...

With this reference:

prompt: id=919212
prompt: printf "%02u\n%02u\n%02u\n" $(($id/10000)) $(($id/100%100)) $(($id%100))

Output:
91
92
12

ropata said...

You could also use bit of perl.

perl -e "print scalar(localtime($unixtime))"

Jadu Saikia said...

@Thanks Ropata

Sneaky Weasel said...

Using %.2d instead of %d will fix the formatting.

Sneaky Weasel said...

To get the 00:00:00 format, use %.2d instead of %d above.

Sneaky Weasel said...

Using %.2d instead of %d will fix the formatting.

© Jadu Saikia www.UNIXCL.com