1

I have a version number with three columns and two digits (xx:xx:xx). Can anyone please tell me how to increment that using shell script.

Min Value
00:00:00

Max Value
99:99:99

Sample IO
10:23:56 -> 10:23:57
62:54:99 -> 62:55:00
87:99:99 -> 88:00:00

5 Answers 5

3

As a one liner using awk, assuming VERSION is a variable with the version in it:

echo $VERSION | awk 'BEGIN { FS=":" } { $3++;  if ($3 > 99) { $3=0; $2++; if ($2 > 99) { $2=0; $1++ } } } { printf "%02d:%02d:%02d\n", $1, $2, $3 }'
Sign up to request clarification or add additional context in comments.

Comments

2

Nothing fancy (other than Bash) needed:

$ ver=87:99:99
$ echo "$ver"
87:99:99
$ printf -v ver '%06d' $((10#${ver//:}+1))
$ ver=${ver%????}:${ver: -4:2}:${ver: -2:2}
$ echo "$ver"
88:00:00

We just use the parameter expansion ${ver//:} to remove the colons: we're then left with a usual decimal number, increment it and reformat it using printf; then use some more parameter expansions to group the digits.

This assumes that ver has already been thorougly checked (with a regex or glob).

Comments

1

It's easy, just needs some little math tricks and bc command, here is how:

#!/bin/bash

# read VERSION from $1 into VER
IFS=':' read -r -a VER <<< "$1"

# increment by 1
INCR=$(echo "ibase=10; ${VER[0]}*100*100+${VER[1]}*100+${VER[2]}+1"|bc)

# prepend zeros
INCR=$(printf "%06d" ${INCR})

# output the result
echo ${INCR:0:2}:${INCR:2:2}:${INCR:4:2}

If you need overflow checking you can do it with the trick like INCR statement.

2 Comments

Doesn't work if major version number is < 10, e.g., 09:00:00.
@gniourf_gniourf yeah, it improved :)
0

This basically works, but may or may not do string padding:

IN=43:99:99
F1=`echo $IN | cut -f1 '-d:'`
F2=`echo $IN | cut -f2 '-d:'`
F3=`echo $IN | cut -f3 '-d:'`

F3=$(( F3 + 1 ))
if [ "$F3" -gt 99 ] ; then F3=00 ; F2=$(( F2 + 1 )) ; fi
if [ "$F2" -gt 99 ] ; then F2=00 ; F1=$(( F1 + 1 )) ; fi

OUT="$F1:$F2:$F3"
echo $OUT

3 Comments

You can use IFS=: read -r F1 F2 F3 <<< "$IN" instead of using cut to split $IN.
@andlrc Cool! I did not know about the Internal Field Separator in bash.
This needs some work to handle leading zeros, both restoring them after the arithmetic and avoiding base-8 arithmetic.
0

try this one liner:

awk '{gsub(/:/,"");$0++;gsub(/../,"&:");sub(/:$/,"")}7'

tests:

kent$  awk '{gsub(/:/,"");$0++;gsub(/../,"&:");sub(/:$/,"")}7' <<< "22:33:99"
22:34:00

kent$  awk '{gsub(/:/,"");$0++;gsub(/../,"&:");sub(/:$/,"")}7' <<< "22:99:99"
23:00:00

kent$  awk '{gsub(/:/,"");$0++;gsub(/../,"&:");sub(/:$/,"")}7' <<< "22:99:88"
22:99:89

Note, corner cases were not tested.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.