1

I'm trying to increment version number by .10, but also keep following zeros. Here is what i have:

printf '%s\n' '1.00' '1.50' '1.90' | perl -i -pe "s/\K.+/$&+0.1/e"

This returns:

1.1
1.6
2

But i want it to return:

1.10
1.60
2.00

Any tips on how to achieve that?

MarkoJ
  • 19
  • 2
  • Does this answer your question? [How to increment version number in a shell script?](https://stackoverflow.com/questions/8653126/how-to-increment-version-number-in-a-shell-script) – Léa Gris Sep 21 '20 at 10:03

5 Answers5

6

When people work out how powerful regexes are, they often start using them everywhere - even when they're not the most appropriate tool.

There's no need for a regex here. What you want is sprintf().

#!/usr/bin/perl

use strict;
use warnings;
use feature 'say';

my @vers = qw(1.00 1.50 1.90);

for (@vers) {
  my $newver = sprintf '%.2f', $_ + .1;

  say "$_ -> $newver";
}

Output:

1.00 -> 1.10
1.50 -> 1.60
1.90 -> 2.00
Dave Cross
  • 68,119
  • 3
  • 51
  • 97
2

First of all,

s/\K.+/$&+0.1/e

is a really weird way to write

$_ += 0.1 if length

And it can apparently be shortened to

$_ += 0.1

Solution:

Replace -p and

s/\K.+/$&+0.1/e

with -n and

printf "%.2f", $_ + 0.1
ikegami
  • 367,544
  • 15
  • 269
  • 518
1

Using awk:

$ printf '%s\n' '1.00' '1.50' '1.90' |
  awk '{printf "%.2f\n",$0+0.1}'

Output:

1.10
1.60
2.00
James Brown
  • 36,089
  • 7
  • 43
  • 59
0

You could also hand it over to zsh. For instance,

export v
for v in 1.00 1.50 1.90
do
    zsh -c 'printf %.2f $((v+0.1))'
done

respectively, if you need to catch the incremented version in a variable,

    new_version=$(zsh -c 'printf %.2f $((v+0.1))')

Of course, if you go so far, you could think of writing your whole script in zsh instead of bash.

user1934428
  • 19,864
  • 7
  • 42
  • 87
0

Plain POSIX shell function:

#!/usr/bin/env sh

newver() {
  version=$1
  major=${version%.*}
  minor=$((${version#*.} + 10))
  if [ $minor -gt 99 ]; then
    minor=0
    major=$((major + 1))
  fi
  printf '%d.%02d\n' $((major)) $((minor))
}

for v in '1.00' '1.50' '1.90'; do
  newver "$v"
done

Output:

1.10
1.60
2.00

Or a one-liner using bc:

for v in 1.00 1.50 1.90;do echo scale=2\;$v+.1|bc;done
Léa Gris
  • 17,497
  • 4
  • 32
  • 41