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

前端 未结 6 2230
难免孤独
难免孤独 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
    

提交回复
热议问题