【问题标题】:Trying to Replacing a string in a file using groovy DSL [duplicate]尝试使用 groovy DSL 替换文件中的字符串 [重复]
【发布时间】:2020-09-03 12:14:13
【问题描述】:

我想将文件中的 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 的新手,不知道我缺少什么,任何建议,不胜感激!

【问题讨论】:

  • 这可能只是一个糟糕的例子,但要提一下:ff 该代码可以工作,它只会用列表中的第一个版本替换所有出现的 VERSION。下一个版本将不再在(相同的)文件中找到 VERSION,因为它已经被替换了。
  • @cfrick 谢谢你的时间,是的,这是一个错误的例子,很抱歉!

标签: groovy jenkins-groovy jenkins-job-dsl


【解决方案1】:

另一种方法是使用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 工具。

【讨论】:

  • 谢谢!是的,这个例子是错误的!
猜你喜欢
  • 2014-03-07
  • 1970-01-01
  • 2018-06-14
  • 2016-07-29
  • 1970-01-01
  • 2017-06-08
  • 1970-01-01
  • 2020-12-19
  • 1970-01-01
相关资源
最近更新 更多