how to replace a string/word in a text file in groovy

前端 未结 6 2220
难免孤独
难免孤独 2020-12-05 22:57

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/

相关标签:
6条回答
  • 2020-12-05 23:31

    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
    
    0 讨论(0)
  • 2020-12-05 23:33

    other simple solution would be following closure:

    def replace = { File source, String toSearch, String replacement ->
            source.write(source.text.replaceAll(toSearch, replacement))
        }
    
    0 讨论(0)
  • 2020-12-05 23:39

    I use this code to replace port 8080 to ${port.http} directly in certain file:

        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.

    0 讨论(0)
  • 2020-12-05 23:44

    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

    0 讨论(0)
  • 2020-12-05 23:44

    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. 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
    
    0 讨论(0)
  • 2020-12-05 23:47

    As with nearly everything Groovy, AntBuilder is the easiest route:

    ant.replace(file: "myFile", token: "NEEDLE", value: "replacement")
    
    0 讨论(0)
提交回复
热议问题