Skip to content

Instantly share code, notes, and snippets.

@willis7
Forked from tamirko/replaceInFile.groovy
Last active August 29, 2015 14:06
Show Gist options
  • Save willis7/33c478e332de7d9e8fc3 to your computer and use it in GitHub Desktop.
Save willis7/33c478e332de7d9e8fc3 to your computer and use it in GitHub Desktop.
/* 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
( 1..9 ).each { fileText = (fileText =~ /James/).replaceFirst("user${it}") }
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