Search code examples
groovy

Change only the numbers of a line in a file


I would like to change only the numbers of a line.

Source file:

IMAGE_VERSION_TD_S=1.108.1.1
IMAGE_VERSION_CPO=1.87.13.1
IMAGE_VERSION_CVM=1.71.1.1

I would like to search for a string like ("IMAGE_VERSION_CPO=") and change only the numbers to 1.90.12.1.

Output file:

IMAGE_VERSION_TD_S=1.108.1.1
IMAGE_VERSION_CPO=1.90.12.1
IMAGE_VERSION_CVM=1.71.1.1

I have tried on this way but it generated a new line on the final file:

def data = readFile(file: pathEnv)
def lines = data.readLines()
def strNewEnv = ''
lines.each {
    String line ->
    if (line.startsWith("IMAGE_VERSION_CPO=")) {
         strNewEnv = strNewEnv + '\n' + 'IMAGE_VERSION_CPO=' + imageVersion
    } else {
         strNewEnv = strNewEnv + '\n' + line
    }
    println line
}

println strNewEnv
writeFile file: directoryPortal+"/${params.ENVIROMENT}/"+envFile, text: strNewEnv

Solution

  • If this is a properties file, use the readProperties step:

    def props = readProperties file: pathEnv, text: "IMAGE_VERSION_CPO=${imageVersion}"
    writeFile file: "${directoryPortal}/${params.ENVIROMENT}/${envFile}", text: props.collect { "${it.key}=${it.value}" }.join("\n")
    

    If, for some reason, this isn't a props file:

    def data = readFile(file: pathEnv)
    data = data.replaceAll(/(?<=IMAGE_VERSION_CPO=)[\d\.]+/, imageVersion)
    writeFile file: "${directoryPortal}/${params.ENVIROMENT}/${envFile}", text: data
    

    There's likely a much better regex for that but it seems to be working