Parsing groovy更新配置文件

Parsing groovy更新配置文件,parsing,properties,groovy,Parsing,Properties,Groovy,我有一个groovy配置文件,看起来像 section1 { prop1 = val1 prop2 = val2 section2 { prop3 = val3 { } // other style properties in this file anotherprop = someval // as well as some other statements println "hello there" 例如,我想编写一个groovy脚本来更改

我有一个groovy配置文件,看起来像

section1 {
    prop1 = val1
    prop2 = val2
    section2 {
       prop3 = val3
    {
}

// other style properties in this file
anotherprop = someval

// as well as some other statements
println "hello there"

例如,我想编写一个groovy脚本来更改prop3的值。在groovy中有没有一种很好的方法来实现这一点?由于该文件包含多种样式的属性以及println,所以比较困难。

据我所知,您希望修改配置文件

由于文件中有
println
和其他语句,因此不能使用configurationSlurper读取文件

我想最简单的方法(但我希望thsi解决方案能获得否决票):使用regsub:

def config = new File('config.groovy').getText()
def newValue = 18
def newConfig = config.replaceAll(/(?ms)(prop3[ \t]*=[ \t]*)([0-9]*)/,'$1'+newValue)
new File('config.groovy').write(newConfig)

在大多数情况下,这应该是相当稳定的…

我考虑过这样做,但它不能很好地处理嵌套属性。例如,如果我在一个街区内有一个prop3,在另一个街区内有一个prop3,你有机会“标记”你的财产吗?也许会有令人沮丧的评论?还是内联评论<代码>myProperty=15//不幸的是,没有,请参阅我对上述问题的评论。顺便问一下:替换属性的用例是什么?我正在使用一些第三方代码,这些代码公开了一些我可以更改的配置文件,我希望以编程方式更改它们。虽然println对属性并不重要,但我希望尽可能地保留文件。在应用程序读取配置后,是否可以修改配置?这样,您的应用程序配置将覆盖第三方应用程序配置?不确定,我必须检查,但我相信所有这些配置文件都是在启动期间读取的。afaik,所有配置文件都已在执行引导代码时读取-您可以使用configSlurper读取另一个配置并覆盖第三方配置。。。