簡體   English   中英

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

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

我正在遵循使用 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)

字符串中的點 (.) 是否弄亂了它? 如果是這樣,正確的語法是什么? 謝謝。

您需要在文件的內容上調用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