Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.
VERSION="4.0beta12"
NEXT_VERSION=?????

Writing an automatic release script, I have the current version in a variable $VERSION, and I would like to calculate the next version as $NEXT_VERSION.

Rule: Increment the integer at the end of the string.
4.0beta12 → 4.0beta13
4.2alpha9 → 4.2alpha10

I have tried with sed/awk/eval but can't make it work. Ideas? Any tool is fine.

share

4 Answers 4

up vote 4 down vote accepted

Assuming you always have some reasonable well-formedness rules (always a non-digit in the version, version always ends in digits), this, however klunky, might be a start:

#!/usr/bin/gawk -f
1 {
    pfx = gensub(/^(.*[^0-9])([0-9]+)$/, "\\1", "")
    patchlevel = gensub(/^(.*[^0-9])([0-9]+)$/, "\\2", "")

    new_pl = (1*patchlevel)+1
    printf "%s%s\n", pfx, new_pl
}

Test:

[0 1066] ~/temp % echo "12.4alpha9" | gawk -f incvers.awk
12.4alpha10
[0 1067] ~/temp % echo "12.4alpha12" | gawk -f incvers.awk
12.4alpha13
[0 1068] ~/temp % echo "12.4alpha-2" | gawk -f incvers.awk
12.4alpha-3
share

No need for anything but Bash:

for version in 12.4alpha9 12.4alpha12 12.4alpha-2; do
    echo -n "$version => ";
    [[ "$version" =~ (.*[^0-9])([0-9]+)$ ]] && version="${BASH_REMATCH[1]}$((${BASH_REMATCH[2]} + 1))";
    echo "$version";
done

The only line really relevant to you, is the one with the regex check [[: it remembers everything leading up to the final number, reuses that and appends the next number.

share
1  
Inside arithmetic evaluation no need to use ${} around the variable: $((BASH_REMATCH[2] + 1)) is enough. –  manatwork Oct 24 '11 at 9:44
    
Thanks, I did not know that! –  janmoesen Oct 24 '11 at 19:03

Try having

MAJOR=4
MINOR=0
STATE="beta"
POINT=9
VERSION=$MAJOR.$MINOR$STATE$POINT
NEXT_VERSION=$MAJOR.$MINOR$STATE$((POINT +1 ))

echo "Next version is $NEXT_VERSION"
# other release stuff here 

Do want this to be a self-rewriting script? I'd suggest something like

tempfile=$( tempfile -d . )
sed -re "s/POINT=[0-9]+/POINT=$(( ++POINT ))/" $0 > $tempfile
chmod +x $tempfile
mv $tempfile $0
share

Here's a portable shell snippet that adds 1 to the number at the end of $current_version.

n=${current_version##*[!0-9]}; p=${current_version%%$n}
next_version=$p$((n+1))

Just because it's simple (well, fairly simple) doesn't mean it's a good idea. Like Andrew, I recommend breaking down your variable definitions into components.

share

This site is currently not accepting new answers.

Not the answer you're looking for? Browse other questions tagged .