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.
Groovy - replaceAll() Replaces all occurrences of a captured group by the result of a closure on that text.
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.
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.
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 (*/).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With