Search code examples
jenkinsjenkins-groovyjenkins-cli

How to trim a set of numbers from a string in Jenkins?


How to trim set of numbers from a sting in Jenkins. This is what I am trying but some how there is one mistake not able to fix it.

def Build_Num = sh(script: "echo ${BUILD_PATH} | awk 'BEGIN {FS="_"};{print $NF}' | sed 's/[A-Za-z]*//g'", returnStdout: true).trim()

BUILD_PATH=ABC/EFGH/ABCD_1.2.3456.78912/

Result should be like this: 1.2.3456.78912

Directly in shell I am trying to achieve with below command but not able to do it in Jenkins:

echo ABC/EFGH/ABCD_1.2.3456.78912/ | awk 'BEGIN {FS="_"};{print $NF}' | sed 's/[A-Za-z]*//g'

Solution

  • You need to escape your $ character for your awk argument, otherwise Groovy will perform string interpolation.

    Of course, we do not want to escape the $ for ${BUILD_PATH}, because in that case we do want string interpolation, we just don't want string interpolation for $NF.

    Try this:

    def Build_Num = (sh script: """echo ${BUILD_PATH} | awk 'BEGIN {FS="_"};{print \$NF}' | sed 's/[A-Za-z]*//g'""", returnStdout: true).trim()