简体   繁体   English

在 Groovy 中如何替换文件中的字符串?

[英]In Groovy how to replace a string in a file?

I'm following the answer given in Replace the string in file using groovy , but am getting an error.我正在遵循使用 groovy 替换文件中的字符串中给出的答案,但出现错误。 I just want to replace, for example我只想替换,例如

From
version=1.1.0

To
version=1.1.1

in some file.在某个文件中。 I do我愿意

String sv1 = '1.1.0'
String sv2 = '1.1.1'
def file = new File(`/some_path/someFile')
def fileText = file.replaceAll("version=$sv1", "version=$sv2")
file.write(fileText)

I get我得到

Caught: groovy.lang.MissingMethodException: No signature of method: java.io.File.replaceAll() is applicable for argument types: (org.codehaus.groovy.runtime.GStringImpl, org.codehaus.groovy.runtime.GStringImpl) values: [version=1.1.0, version=1.1.1]
groovy.lang.MissingMethodException: No signature of method: java.io.File.replaceAll() is applicable for argument types: (org.codehaus.groovy.runtime.GStringImpl, org.codehaus.groovy.runtime.GStringImpl) values: [version=1.1.0, version=1.1.1]
    at pre-push.updatePatchVersion(pre-push:154)
    at pre-push.compareVersions(pre-push:188)
    at pre-push.run(pre-push:219)

Are the dots (.) in the string messing it up?字符串中的点 (.) 是否弄乱了它? What's the proper syntax if so?如果是这样,正确的语法是什么? Thanks.谢谢。

您需要在文件的内容上调用replaceAll() ,而不是在File实例本身上。

def fileText = file.text.replaceAll("version=$sv1", "version=$sv2")

这将在一行中完成您的整个任务

new File(`/some_path/someFile').text=new File(`/some_path/someFile').getText().replaceAll("version=1.1.0", "version=1.1.1")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM