Search code examples
jenkinsgroovyjenkins-pipeline

Replacing all new line charc in a file with a special character "#" in groovy


How to replace all "\n" occurrences in a text file with "#" using groovy in a jenkins pipeline


Solution

  • This should work. Use the find operator ~ in Groovy

    def parsedText = readFile("input.groovy").replaceAll(~/\n/, "#")
    writeFile file: "output.groovy", text: parsedText
    

    EDIT If you use Declarative Pipeline Syntax, the working code is as follows:

    pipeline {
        agent any
        stages {
            stage ('Print'){
                steps {
                    script {
                        def inputText = readFile file: "1.groovy" 
                        inputText = inputText.replaceAll(~/\n/, "#")       
                        writeFile file: "2.groovy", text: inputText
                    }
                
                }
            }
        }
    }