Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace a string in a file using jenkins pipeline script

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.

like image 626
Nageswar Reddy Avatar asked Dec 05 '25 15:12

Nageswar Reddy


2 Answers

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
like image 152
ycr Avatar answered Dec 08 '25 03:12

ycr


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'
    )
  ]
)
like image 38
Wafeeq Avatar answered Dec 08 '25 03:12

Wafeeq



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!