Skip to content

Instantly share code, notes, and snippets.

@lineuve
Forked from tamirko/replaceInFile.groovy
Created October 12, 2019 04:22
Show Gist options
  • Select an option

  • Save lineuve/546e69565c14f29765263b375783e766 to your computer and use it in GitHub Desktop.

Select an option

Save lineuve/546e69565c14f29765263b375783e766 to your computer and use it in GitHub Desktop.
replace string in a file in groovy example
/* Groovy Usage:
The following example replaces:
the 1st occurrence of "James" in data.txt with "user1",
the 2nd occurrence of "James" in data.txt with "user2",
the 3rd occurrence of "James" in data.txt with "user3",
..
the 9th occurrence of "James" in data.txt with "user9".
*/
def myFile = new File("data.txt")
def fileText = myFile.text
for ( index in 1..9 ) {
fileText = (fileText =~ /James/).replaceFirst("user${index}")
}
myFile.write(fileText)
/* Usage in Cloudify:
The following code snippet replaces all the occurrences of 8080
with the current actual http port and all the occurrences of 8009
with the current actual AJP port.
*/
def config = new ConfigSlurper().parse(new File("tomcat-service.properties").toURL())
def context = ServiceContextFactory.getServiceContext()
def home = "${context.serviceDirectory}/${config.name}"
portIncrement = 0
def serverXmlFile = new File("${home}/conf/server.xml")
def serverXmlText = serverXmlFile.text
portReplacementStr = "port=\"${config.port + portIncrement}\""
ajpPortReplacementStr = "port=\"${config.ajpPort + portIncrement}\""
serverXmlText = serverXmlText.replace("port=\"8080\"", portReplacementStr)
serverXmlText = serverXmlText.replace("port=\"8009\"", ajpPortReplacementStr)
serverXmlFile.write(serverXmlText)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment