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.

Jeff Schaller
  • 66,199
  • 35
  • 114
  • 250
djent
  • 11
  • 3

2 Answers2

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 –  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 03:31
  • @djent - could you please update the question ? –  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
Stephen Harris
  • 42,369
  • 5
  • 94
  • 123