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.
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
I have a question about how to get sub content after running readFile in Jenkins.
I print the content after readFile method of groovy in Jenkins
the content looks like this
Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: asdfasdf
Team: {org=org1, team=team1}
ABCD: {org=org2, team=team2}
ABCDE: {org=org3, team=team3}
Bundle-Vendor: xxxxx
I just want to get this line in the content
Team: {org=org1, team=team1}
ABCD: {org=org2, team=team2}
ABCDE: {org=org3, team=team3}
but how??
any Solutions?
The content of your file looks like it is a properties file, so you can use the readProperties keyword which is part of the Pipeline Utility Steps to read the file into a map, allowing you easy access to all the values:
readProperties: Read properties from files in the workspace or text.
Reads a file in the current working directory or a String as a plain text Java Properties file. The returned object is a normal Map with String keys. The map can also be pre loaded with default values before reading/parsing the data.
You now have easy access to the keys and values.
In your case it can look like:
def props = readProperties file: 'YOUR_FILE_PATH'
// You can now access all values from the props map
def content = "Team: ${props.Team}"
If you just want the line based on parsing the file content you can read the file, split the content by new lines and use something like the following:
def lines = readFile('YOUR_FILE_PATH').split("\n").trim()
// Get a constant line
def content = lines[4]
// Get a line by prefix
def content = lines.find{ it.startsWith('Team')}
I am trying to concatenate a file name by appending strings and the build number within the steps script in my Jenkinsfile and then pass it to create a zipFile, but the environment build number does not get recognized in the concatenated string. What is the correct syntax?
stage ('Publish Reports') {
steps {
script {
def fileName = "reportFiles/" + '${env.BUILD_NUMBER}' + ".zip"
zip zipFile: fileName, archive: false, dir: 'target/site/main'
}
}
}
With this syntax, the fileName gets saved as:
reportFiles/${env.BUILD_NUMBER}.zip,
instead of the actual build number, for example :
reportFiles/1.zip
Actually, i found a resolution of the issue, it was a silly syntax error. The correct declaration was:
def fileName = "reportFiles/${env.BUILD_NUMBER}.zip"
I am using "Parameterized Trigger Plugin" to trigger child job. I am using "parametres from properties file" and in the "Use properties from file" in need to pass the name of the file as a variable...I get this error.
[parameterized-trigger] Properties file $propeties_file did not exist.
enter image description here
If you click on the ? you will see the usage / syntax for the property file:
Comma seperated list of absolute or relative paths to file(s) that
contains the parameters for the new project. Relative paths are
originated from the workspace. The file should have KEY=value pairs,
one per line (Java properties file format). Backslashes are used for
escaping, so use "\\" for a single backslash. Current build
paramenters and/or environment variables can be used in form: ${PARAM}
or $PARAM.
So your file needs to exist and you should put the path to the file to where you are putting your $properties_file - I don't believe it will accept a variable, you should put the file name in there.
A sample pipeline to trigger parameterize build using parameters from the properties file
pipeline {
agent any
stages {
stage('S1') {
steps {
echo 'In S1'
sh '''
echo "param1=value1" > my.properties
echo "param2=value2" >> my.properties
'''
}
}
stage('s2'){
steps {
script {
def props = readProperties file:"${WORKSPACE}/my.properties"
build job: 'called_job', parameters: props.collect {string(name: it.key, value: it.value)}
}
}
}
}
}
I am using jenkins for automated deployment.
I needs to modify xml tag value in xml file using groovy script. I am using below groovy code. When I try to edit xml tag value I am receiving error unclassified field xml.uti.node error.
Node xml = xmlParser.parse(new File("c:/abc/test.xml"))
xml.DeployerServer.host[0] = '172.20.204.49:7100'
FileWriter fileWriter = new FileWriter("c:/abc/test.xml")
XmlNodePrinter nodePrinter = new XmlNodePrinter(new PrintWriter(fileWriter))
nodePrinter.setPreserveWhitespace(true)
nodePrinter.print(xml)
I need to modify host tag value and host is available inside DeployerServer tag.
Any help will be much appreciated.
Here is the script, comments in-line:
//Create file object
def file = new File('c:/abc/test.xml')
//Parse it with XmlSlurper
def xml = new XmlSlurper().parse(file)
//Update the node value using replaceBody
xml.DeployerServer.host[0].replaceBody '172.20.204.49:7100'
//Create the update xml string
def updatedXml = groovy.xml.XmlUtil.serialize(xml)
//Write the content back
file.write(updatedXml)
I was wanting to read / manipulate the CSProj file and NUSPEC files in a Pipeline script. I could not get passed the parseText() without the dreaded "SAXParseException: Content is not allowed in prolog".
There are quite a few threads about this error message. What wasn't clear is that both CSProj and NUSPEC files are UTF-8 with BOM - BUT this is invisible!
To make it worse I've been trying to automate the NUSPEC file creation, and there is no way I can tell the tools to change file encoding.
The answers above helped solve my issue, and once I added code to look for 65279 as the first character (and deleted it). I could then parse the XML and carry out the above.
There didn't seem to be good thread to put this summary on, so added it to a thread about Jenkins, Groovy & XML files which is where I found this "known Java" issue.
I used powershell to do this change in app.config file.
My problem was with passwords. So, I created a Credential, in jenkins, to store the password.
If you do not need to work with credential, just remove the withCredentials section
Here is part of my jenkinsfile:
def appConfigPath = "\\server\folder\app.config"
stage('Change App.Config'){
steps{
withCredentials([string(credentialsId: 'CREDENTIAL_NAME', variable: 'PWD')]) {
powershell(returnStdout: true, script: '''
Function swapAppSetting {
param([string]$key,[string]$value )
$obj = $doc.configuration.appSettings.add | where {$_.Key -eq $key }
$obj.value = $value
}
$webConfig = "'''+appConfigPath+'''"
$doc = [Xml](Get-Content $webConfig)
swapAppSetting 'TAG_TO_MODIFY' 'VALUE_TO_CHANGE'
$doc.Save($webConfig)
''')
}
}
}
Don`t forget to update your powershell. (minimum version 3)
I'm hoping this is not a bug and that I'm just doing something wrong. I have a Jenkins (v2.19.1) Pipeline job and in it's groovy script, I need to search and replace some text in an existing text file, on a Windows node.
I've used fart.exe and powershell to do the search and replace, but I would really like to do this with just the groovy in Jenkins and eliminate dependency on fart/powershell/etc. and make this code more reusable on both linux and windows nodes.
After much googling and trying various approaches, the closest I got was to use readFile and writeFile. However, I've not been able to get writeFile to create a UTF-8 file. It creates an ANSI file even when I specify UTF-8 (assuming I'm doing it correctly).
Here's what I have so far...
def fileContents = readFile file: "test.txt", encoding: "UTF-8"
fileContents = fileContents.replace("hello", "world")
echo fileContents
writeFile file: "test.txt", text: fileContents, encoding: "UTF-8"
I've confirmed with multiple text editors that the test.txt file is UTF-8 when I start, and ANSI after the writeFile line. I've tried all combinations of including/not-including the encoding property and "utf-8" vs "UTF-8". But in all cases, the file is written out as ANSI (as reported by both Notepad++ and VS Code). Also, a question mark (HEX 3F) is added as the very first character of the file.
The echo line does not show the extra 3F character, so it seems the issue is in the writeFile line.
Your code looks correct. See that ANSI and UTF-8 are the same if you are using just non accented chars and numbers. Try to have some accented letters (áéíóúç) in your file that the editor will probably recognize it as an UTF-8 file.
You must use the Jenkins pipeline writeFile function. This is a special Jenkins method to write files inside your workspace. The default Java File objects won't work.
To specify the encoding, you must use named parameters. Here is a an example:
writeFile(file: "filename.txt", text: "áéíóú", encoding: "UTF-8")
This will create at the root of your workspace, a file named filename.txt with "áéíóú" as content and encoded as UTF-8.
BTW, if you have full control of the file you must search and replace, consider using Groovy's builtin SimpleTemplateEngine