如何在groovy中替换文本文件中的字符串/单词

ger*_*etd 30 groovy

您好我正在使用groovy 2.1.5并且我必须编写一个代码,该代码显示具有给定路径的目录的contens /文件,然后它对文件进行备份并从文件中替换单词/字符串.这是我用来尝试替换所选文件中的单词的代码

String contents = new File( '/geretd/resume.txt' ).getText( 'UTF-8' ) 
contents = contents.replaceAll( 'visa', 'viva' )
Run Code Online (Sandbox Code Playgroud)

这里也是我的完整代码,如果有人想以更有效的方式修改它,我会欣赏它,因为我正在学习.

def dir = new File('/geretd')
dir.eachFile { 
    if (it.isFile()) {
        println it.canonicalPath
    }
}

copy = { File src,File dest-> 

    def input = src.newDataInputStream()
    def output = dest.newDataOutputStream()

    output << input 

    input.close()
    output.close()
}

//File srcFile  = new File(args[0])
//File destFile = new File(args[1])

File srcFile  = new File('/geretd/resume.txt')
File destFile = new File('/geretd/resumebak.txt')
copy(srcFile,destFile)

x = " "
println x

def dire = new File('/geretd')
dir.eachFile { 
    if (it.isFile()) {
        println it.canonicalPath
    }
}

String contents = new File( '/geretd/resume.txt' ).getText( 'UTF-8' ) 
contents = contents.replaceAll( 'visa', 'viva' )
Run Code Online (Sandbox Code Playgroud)

tim*_*tes 33

作为将整个文件加载到内存中的替代方法,您可以依次执行每一行

new File( 'destination.txt' ).withWriter { w ->
  new File( 'source.txt' ).eachLine { line ->
    w << line.replaceAll( 'World', 'World!!!' ) + System.getProperty("line.separator")
  }
}
Run Code Online (Sandbox Code Playgroud)

当然这(和dmahapatro的答案)依赖于你正在替换的单词而不是跨行

  • 根据我的经验,这个解决方案吞噬了行分隔符.第3行为w << line.replaceAll('World','World !!!')+ System.getProperty("line.separator")效果更好.+1无论如何. (7认同)

Mic*_*ing 26

与几乎所有Groovy一样,AntBuilder是最简单的路径:

ant.replace(file: "myFile", token: "NEEDLE", value: "replacement")
Run Code Online (Sandbox Code Playgroud)

  • @IgorGanapolsky @ paulo-pedroso你可以使用`ant.replaceregexp(file:'myFile',match:'my regexp',replace:'my replacement string')` (2认同)

小智 13

我使用此代码直接在某些文件中将端口8080替换为$ {port.http}:

    def file = new File('deploy/tomcat/conf/server.xml')
    def newConfig = file.text.replace('8080', '${port.http}')
    file.text = newConfig
Run Code Online (Sandbox Code Playgroud)

第一个字符串将文件的一行读入变量.第二个字符串执行替换.第三个字符串将变量写入文件.

  • 不妨更新这个以使用`replaceAll` (2认同)
  • 这是一个非常有用的答案,但我想补充一下,如果您想替换多个字符串,只需在上一个替换后附加 ```replace``` 方法即可: ```file.text.replace('8080', '${port.http}').replace('str', 'new str')``` (2认同)

dma*_*tro 9

请参阅此答案,更换图案.可以使用相同的原理来替换字符串.

样品

def copyAndReplaceText(source, dest, Closure replaceText){
    dest.write(replaceText(source.text))
}

def source = new File('source.txt') //Hello World
def dest = new File('dest.txt') //blank

copyAndReplaceText(source, dest) {
    it.replaceAll('World', 'World!!!!!')
}

assert 'Hello World' == source.text
assert 'Hello World!!!!!' == dest.text
Run Code Online (Sandbox Code Playgroud)


小智 5

使用“文件”对象的答案是好的且快速的,但是通常会导致以下错误,当然可以避免,但是以失去安全性为代价:

不允许脚本使用新的java.io.File java.lang.String。管理员可以决定是批准还是拒绝此签名。

此解决方案避免了上面提出的所有问题:

String filenew = readFile('dir/myfile.yml').replaceAll('xxx','YYY')
writeFile file:'dir/myfile2.yml', text: filenew
Run Code Online (Sandbox Code Playgroud)