Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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. 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' ) 
like image 690
geretd Avatar asked Jun 30 '13 23:06

geretd


People also ask

How do I replace a string in Groovy?

replaceAll() is a function in groovy that replaces all occurrences of a string with a specified string.

How do I replace text in a file?

Open the text file in Notepad. Click Edit on the menu bar, then select Replace in the Edit menu. Once in the Search and Replace window, enter the text you want to find and the text you want to use as a replacement. See our using search and replace and advanced options section for further information and help.


1 Answers

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

like image 87
tim_yates Avatar answered Sep 17 '22 14:09

tim_yates