【问题标题】:In Groovy how to replace a string in a file?在 Groovy 中如何替换文件中的字符串?
【发布时间】:2019-12-02 21:47:45
【问题描述】:

我正在关注Replace the string in file using groovy 中给出的答案,但出现错误。我只是想替换,例如

From
version=1.1.0

To
version=1.1.1

在某个文件中。我愿意

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)

我明白了

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)

字符串中的点 (.) 是否搞砸了?如果是这样,正确的语法是什么?谢谢。

【问题讨论】:

    标签: groovy


    【解决方案1】:

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

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

    【讨论】:

    • 我提到的链接中的答案是错误的。这是正确的做法。
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2023-03-25
      • 2014-03-07
      • 1970-01-01
      • 1970-01-01
      • 2023-02-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多