I am trying to edit a file package.json and trying to replace a string("version:1") inside it using jenkins pipeline script. I have written below script but its not working.
def readContent = readFile './package.json'
updatedProp = readContent.replaceAll("version:.*","version:${env.ReleaseNumber}.${BUILD_NUMBER},")
writeFile file: './package.json', text: "${updatedProp}"
package.json file contains below content.
{
"name": "application",
"version": "1.0.0"
}
I request to correct me and help me building the code.
Check the following code.
def data = readJSON file: 'package.json'
String val = "${ReleaseNumber}"
data['version'] = val
writeJSON file: 'package.json', json: data, overwrite: true
Update with prettyfy
You will have to import JsonOutput hence add import groovy.json.JsonOutput before the pipeline.
def data = readJSON file: 'package.json'
String val = "${ReleaseNumber}"
data['version'] = val
def formtted = JsonOutput.prettyPrint(JsonOutput.toJson(data))
writeFile file: 'package.json', text: formtted, overwrite: true
Jenkins plugin Content Replace can also be used with regular expressions like this
contentReplace(
configs: [
fileContentReplaceConfig(
configs: [
fileContentReplaceItemConfig(
search: '(Version=)([0-9]+\\.[0-9]+\\.[0-9]+)',
replace: '$11.0.${BUILD_ID}',
matchCount: 1,
verbose: false,
)
],
fileEncoding: 'UTF-8',
'versions.txt'
)
]
)
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