Cannot replace line after string match in jenkins pipeline using variables

Viewed 15095

I need to replace a line in a file. If the line starts with the term "url", I need to replace the value.

file.txt --

...
url : http://www.google.com
..

I need to change this value to url : http://www.facebook.com

I tried the following code but it did not work -

FACEBOOK_URL = "http://www.facebook.com"
sh("sed -i \\"s?^url.*\\$?url: ${FACEBOOK_URL}?\\" file.txt")

I'm using a Jenkins Pipeline. I need to replace the string using a variable.

2 Answers

Jenkins 2 Pipeline builds use Groovy and it is very easy to read the file using readfile and then we can do the changes

def text = readFile "file.txt"
text.replaceAll("url.*", "url: ${FACEBOOK_URL}")

The above code will help in replacing the text in the file, if you want to write the content to file, you can use writeFile

You can use this for replacing a string in a file in Jenkins 2 Pipeline builds:

def text = readFile file: "file.txt"
text = text.replaceAll("%version%", "${VERSION}")
writeFile file: "file.txt", text: text
Related