1

What is the simplest way to increment the numbers in this string 01:02:99?

Expected output: 01:03:00

I'm hoping for a sed response, but I don't think it would be simple.

  • What would that "01:02:99" be? Is it a shell variable ? – gerhard d. Jul 12 '16 at 6:30
  • What is that, time? a date? what's the incremented value then? – chaos Jul 12 '16 at 6:33
  • integer. my mistake – djent Jul 12 '16 at 6:35
  • so the incremented value you want is 01:03:00 then? – schaiba Jul 12 '16 at 6:37
  • yes.01:03:00 is right. Shell variable too. – djent Jul 12 '16 at 7:03
3

You could use awk.

$ echo 01:02:99 | awk -vINC_BY=1 -F: '{
    $3 += INC_BY; 
    $2 += int( $3 / 100 );
    $1 += int( $2 / 100 );
    printf("%02d:%02d:%02d\n", $1, $2 % 100, $3 % 100);
}'
01:03:00

This assumes that you want to increment by one. Change 'INC_BY' to the value you want to increase the number by.

Using sed is not a good idea.

  • Thanks. How would I increment it by 'x' amount? – djent Jul 12 '16 at 17:27
  • @djent I've updated the answer – DarkHeart Jul 12 '16 at 22:59
  • Thanks again your too kind. I should've just gotten to the point. I want to increment the 46 and 48 in the string by x amount. how would that work for: 1 00:00:46,666 --> 00:00:48,751 Eyes on Kahili objective. – djent Jul 13 '16 at 3:31
  • @djent - could you please update the question ? – DarkHeart Jul 13 '16 at 11:14
2

This can be done in bash...

First strip off the : to treat it as an integer, then add 1. Because of leading zero's we need to force base 10. The syntax would be similar to

let x=10#$(echo $x | tr -d :)+1

Then we can use printf and some bash arithmetic to put the : back in.

printf %02d:%02d:%02d $((x/10000%100)) $((x/100%100)) $((x%100))

We can put this together: e.g.

$ x=01:02:99
$ let x=10#$(echo $x | tr -d :)+1
$ x=$(printf %02d:%02d:%02d $((x/10000%100)) $((x/100%100)) $((x%100)))
$ echo $x
01:03:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.