0

I am trying to append 5.34.03 number to 5.34.04 by using the following command

$ awk '{print 5.34.03 + 0.0.1}'
5.340.030.1

Expected output

5.34.13

I tried with many methods, eg. let, but it didn't work.

  • If it works like floats, shouldn't the result be 5.34.13? – choroba Apr 24 at 13:11
  • @choroba ah, you're right. thanks, will modify the question. – smc Apr 24 at 13:13
  • 4
    Appending 5.34.03 to 5.34.04 would surely result in 5.34.045.34.03? Why do you call these strings "numbers"?. No numbers, not even floating point numbers, have multiple decimal dots in them. – Kusalananda Apr 24 at 13:21
1

Assuming your minor version and patch version numbers should be 2 characters, you can use this awk script:

parse.awk

BEGIN { FS = "[ .]"; OFS = "." }

function tonum(s) {
  if( length(s) < 2 )
    s *= 10
  return s
}

function tover(n) {
  if( n < 10 )
    n = "0" n
  return n
}

{
  print $1 + $4, tover( tonum($2) + tonum($5) ), tover( tonum($3) + tonum($6) )
}

Run it like this:

echo 5.34.03 0.0.1 | awk -f parse.awk

Output:

5.34.13
2

In bash, you can split each version string using IFS and populate an array with its numbers. Then use parameter expansion to get lengths of the numbers and use printf to format the resulting numbers:

#! /bin/bash
v=5.34.03
a=0.0.1

IFS=.
v=($v)
a=($a)

shopt -s extglob
for ((i=0; i<${#v[@]}; i++)) ; do
    v[i]=${v[i]%%+(0)}
    a[i]=${a[i]%%+(0)}
    v_length=${#v[i]}
    a_length=${#a[i]}
    v[i]=${v[i]##+(0)}
    a[i]=${a[i]##+(0)}
    if (( v_length < a_length )) ; then
        length=$a_length
        (( v[i] *= 10 ** (a_length - v_length) ))
    else
        length=$v_length
        (( a[i] *= 10 ** (v_length - a_length) ))
    fi
    (( v[i] += a[i] ))
    v[i]=$(printf %0"$length"d ${v[i]})
done
IFS=.
echo "${v[*]}"

IFS=$' \t\n'

I needed to handle leading and trailing zeroes as numbers like 010 are treated as octal.

  • thanks. It works fine until 09 (e.g. 5.34.09), after that if I try to append 09 to 10, it is not working. – smc Apr 27 at 15:24
  • What do you mean by "not working"? – choroba Apr 27 at 19:55

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.