James
James

Reputation: 3815

Bumping version string using sed/regex/bash script

I am currently building a CI pipeline that handles incrementing version from a maven pom.xml file. The pom file looks something like this:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://maven.apache.org/POM/4.0.0"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <artifactId>myApp</artifactId>
    <version>1.0.0-SNAPSHOT</version>

    <parent>
        <groupId>com.acme.project</groupId>
        <artifactId>parentApp</artifactId>
        <version>1.0.0-SNAPSHOT</version>
    </parent>

    <dependencies>
        <!-- internal libs -->
        <dependency>
            <groupId>...

I want to perform the following:

  1. Extract the application version (first occurrence of ), i.e. 1.0.0-SNAPSHOT and replace it with 1.0.0
  2. Bump up the version (1.0.1) and append SNAPSHOT to it (1.0.1-SNAPSHOT)

Since I am using Teamcity, I am limited to using bash/sed/regex for this string manipulation. For step 1 I have done something like this:

sed -i -e '1,/<version>1.0.0-SNAPSHOT<\/version>/s/<version>1.0.0-SNAPSHOT<\/version>/<version>1.0.0<\/version>/' pom.xml

The problem is that I am hardcoding the version - this could be 1.0.2-SNAPSHOT, so I need a way to extract this in a flexible way. For step 2, I have no idea how to do it with a primitive tool like sed/regex.

Upvotes: 0

Views: 663

Answers (1)

Nahuel Fouilleul
Nahuel Fouilleul

Reputation: 19305

with bash and grep

# extract the version
v=$(grep -m1 -o '[^<>]*-SNAPSHOT' pom.xml)
[[ $v ]] || { echo "failed to extract version"; exit 1;}
# bumped version remove -SNAPSHOT suffix
bv=${v%-SNAPSHOT}
# new version (split on last dot)
nv=${bv%.*}.$((${bv##*.}+1))

or driectly with perl

perl -i -pe 's/([^<>]*)(\d+)-SNAPSHOT/$1.($2+1)/e' pom.xml

Upvotes: 2

Related Questions