简体   繁体   English

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

[英]how to replace a string/word in a text file in groovy

Hello I am using groovy 2.1.5 and I have to write a code which show the contens/files of a directory with a given path then it makes a backup of the file and replace a word/string from the file.您好,我正在使用 groovy 2.1.5,我必须编写一个代码来显示具有给定路径的目录的内容/文件,然后它会备份文件并替换文件中的单词/字符串。 here is the code I have used to try to replace a word in the file selected这是我用来尝试替换所选文件中的单词的代码

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

also here is my complete code if anyone would like to modify it in a more efficient way, I will appreciate it since I am learning.这也是我的完整代码,如果有人想以更有效的方式修改它,我会很感激,因为我正在学习。

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' )

As an alternative to loading the whole file into memory, you could do each line in turn作为将整个文件加载到内存中的替代方法,您可以依次执行每一行

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

Of course this (and dmahapatro's answer ) rely on the words you are replacing not spanning across lines当然,这(以及dmahapatro 的回答)依赖于您要替换的单词而不是跨行

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

ant.replace(file: "myFile", token: "NEEDLE", value: "replacement")

I use this code to replace port 8080 to ${port.http} directly in certain file:我使用此代码直接在某些文件中将端口 8080 替换为 ${port.http}:

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

The first string reads a line of the file into variable.第一个字符串将文件的一行读入变量。 The second string performs a replace.第二个字符串执行替换。 The third string writes a variable into file.第三个字符串将变量写入文件。

Answers that use "File" objects are good and quick, but usually cause following error that of course can be avoided but at the cost of loosen security:使用“文件”对象的答案既好又快,但通常会导致以下错误,这些错误当然可以避免,但代价是降低安全性:

Scripts not permitted to use new java.io.File java.lang.String.脚本不允许使用新的 java.io.File java.lang.String。 Administrators can decide whether to approve or reject this signature.管理员可以决定是批准还是拒绝此签名。

This solution avoids all problems presented above:此解决方案避免了上述所有问题:

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

Refer this answer where patterns are replaced.请参阅此答案,其中替换了模式。 The same principle can be used to replace strings.相同的原理可用于替换字符串。

Sample样本

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

other simple solution would be following closure:其他简单的解决方案是以下关闭:

def replace = { File source, String toSearch, String replacement ->
        source.write(source.text.replaceAll(toSearch, replacement))
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM