How to increment version number in a shell script?

前端 未结 11 2082
执念已碎
执念已碎 2020-11-29 23:47

The following simple version control script is meant to find the last version number of a given file, increment it, run a given command with the newly created file (e.g., ed

11条回答
  •  情书的邮戳
    2020-11-30 00:27

    Here is an even shorter version that also supports a postfix (nice for -SNAPSHOT)

    $ cat versions
    1.2.3.44
    1.2.3.9
    1.2.3
    9
    42.2-includes-postfix
    
    $ perl -pe 's/^((\d+\.)*)(\d+)(.*)$/$1.($3+1).$4/e' < versions
    1.2.3.45
    1.2.3.10
    1.2.4
    10
    42.3-includes-postfix
    

    Explanation

    I used regex to capture 3 parts. The stuff before the last position, the number to increment, and the stuff after.

    • ((\d+\.)*) - stuff of the from 1.1.1.1.1.
    • (\d+) - the last digit
    • (.*) - the stuff after the last digit

    I then use the e option to allow expressions in the replace part. Note with the e option \1 becomes a variable $1 and you need to concatenate variables with the dot operator.

    • $1 - the capture group of 1.1.1.1.1.
    • ($3+1) - increment the last digit. note $2 is used in the sub group of $1 to get the repeated 1.
    • $4 - the stuff after the last digit

提交回复
热议问题