Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I want to have a shell script with a parameter specifying some time. Is there already an existing way to transform time expressions ala: 1d, 34m, 3s, or 0.456h, or 23ms into lets say just milliseconds, or hours?, before I start coding it by my own? I primarily use Ubuntu, but other OS specific solutions would also be interesting.

It's no problem that other tools like perl, python or awk might be involved.

share|improve this question
up vote 2 down vote accepted

Well here's a quick dirty Perl example on converting to miliseconds a string with following format: "Ad Bh Cm Ds" where A, B, C, and D are values for day, hour, minute and second respectively. Order does not matter, but repetition is not contemplated (e.g. only first 'd' appearance will be processed, others will be ignored).

#!/usr/bin/perl

use strict;

my @markers = ('d', 'h', 'm', 's');
my @converter = (24*60*60*1000, 60*60*1000, 60*1000, 1000);

my $string = $ARGV[0];
my $total_ms = 0;

while(@markers)
{
    my $cur_mark = shift(@markers);
    my $cur_convert = shift(@converter);
    if ($string =~ m/$cur_mark/)
    {
        my $pre = $`;
        $pre =~ m/\b/;
        $total_ms += $' * $cur_convert;     
    }
}

print("Total miliseconds = $total_ms\n");

Usage examples:

./foo.pl "2m 2s"
Total miliseconds = 122000
./foo.pl "0.5h 0.5s"
Total miliseconds = 1800500
share|improve this answer
    
Btw this should work no matter what OS you're running in. – m0skit0 Aug 24 '11 at 10:57
2  
If you're using parallel arrays, you probably want a hash. I'd suggest %markers = ( 'd' => 24*60*60*1000, 'h' => 60*60*1000 ), and then foreach $marker (keys(%markers))... – dannysauer Aug 24 '11 at 19:20
    
You could then make the if statement more like if($string =~ /(\d+)$marker\b/){ $total += $1 * $markers{$marker} } – dannysauer Aug 24 '11 at 19:23

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .