Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot replace line after string match in jenkins pipeline using variables

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.

like image 401
jdoecool Avatar asked Oct 23 '18 14:10

jdoecool


People also ask

How do I replace a string in Groovy?

Groovy - replaceAll() Replaces all occurrences of a captured group by the result of a closure on that text.

How do I set environment variable in Jenkins pipeline stage?

Setting Stage Level Environment Variable It is by using the env variable directly in the script block. We can define, let us say, USER_GROUP and display it. You will see that the underlying shell also has access to this environment variable. You can also set an environment variable using withEnv block.

How do you define a variable in Jenkins scripted pipeline?

Variables in a Jenkinsfile can be defined by using the def keyword. Such variables should be defined before the pipeline block starts. When variable is defined, it can be called from the Jenkins declarative pipeline using ${...} syntax.

How do I comment multiple lines in Jenkins?

Block Comments. Block comments in Jenkinsfile are used to comment out a block of code. Again, the pattern is similar to Java and C++. A block comment starts with a forward-slash followed by an asterisk (/*) and ends with an asterisk followed by a forward-slash (*/).


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

like image 114
Thiru Avatar answered Nov 15 '22 07:11

Thiru


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
like image 34
Sebastian Viereck Avatar answered Nov 15 '22 08:11

Sebastian Viereck