Replace the string in file using groovy

谁说我不能喝 提交于 2019-12-14 02:43:59

问题


I have got a file with name "silent.txt". This file is having a line as follows

bop4InstallDir = myProps.cordys_install_dir + "/" + instanceName

I want to replace the above text with

bop4InstallDir = "/abc/xyz/pqr"

Using groovy script how do I accomplish this? Please help.


回答1:


Not very elegant, but this should work.

def file = new File("silent.txt")

file.text = file.text.replace('bop4InstallDir = myProps.cordys_install_dir + "/" + instanceName', 
'bop4InstallDir = "/abc/xyz/pqr"')



回答2:


Is silent.txt well formatted property file? In this case you can use a various ways to access them, much more secure, than dumb replace.

Look groovy: How to access to properties file? or ConfigSlurper




回答3:


The following code worked:

def file = new File("silent.txt")
def fileText = file.replaceAll("bop4InstallDir\\ \\=\\ myProps.cordys_install_dir\\ \\+\\ \"\\/\"\\ \\+\\ instanceName", "bop4InstallDir\\ \\=\\ \"/opt/cordys/bop4/defaultInst1\"")
    file.write(fileText);


来源:https://stackoverflow.com/questions/21670269/replace-the-string-in-file-using-groovy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!