尝试使用 groovy DSL 替换文件中的字符串

Trying to Replacing a string in a file using groovy DSL

我想将文件中的 VERSION 占位符替换为变量 version 值,但我 运行 出现以下错误:

def versions = ["8.8.0", "9.9.0"]
versions.each { version ->
    def file = new File("$Path/test.url")
        def fileText = file.replaceAll("VERSION", "${version}")
            file.write(fileText);

错误:

groovy.lang.MissingMethodException: No signature of method: java.io.File.replaceAll() is applicable for argument types: (java.lang.String, org.codehaus.groovy.runtime.GStringImpl) values: [VERSION, 8.8.0]

我是 groovy dsl 的新手,不确定我缺少什么,任何建议,不胜感激!

另一种方法是使用 groovy 文件 .text 属性:

def f = new File('sample-file.txt')
f.text = f.text.replaceAll('VERSION', '8.8.0')

就像@cfrick 提到的那样,对多个版本执行替换操作没有多大意义,因为只有第一个版本才能真正找到 VERSION 字符串。

运行 以上示例文件:

─➤ groovy solution.groovy
─➤ 

将导致字符串被替换:

─➤ diff sample-file.txt_original sample-file.txt
1c1
< Dolore magna aliqua. VERSION Ut enim ad minim veniam.
---
> Dolore magna aliqua. 8.8.0 Ut enim ad minim veniam.

其中 diff 是一个 linux 用于比较两个文件的工具。