16 April 2014

Groovy script for replace text in files


def matchPattern = ~/.*.xml/
def directoryBase = "C:/MyProyectDirectory"
def oldText = "web-app"
def newText = "appweb"

println "---------------------------------------------------------------------------------------------"
new File(directoryBase).eachDirRecurse() { dir -> 
    dir.eachFileMatch(matchPattern) { file -> 
     
      boolean encontrado = false
      def coincidencias = []
      file.eachLine {
            // condition to detect match
            ln -> if ( ln.contains(oldText) ) {
                    encontrado = true
                    coincidencias << "\t\t" + ln
            }
       }

      if(encontrado==true){
        println file.getPath() 
        coincidencias.each{ println "found->$it" }
       
        def fileText = file.text
        fileText = (fileText =~ oldText).replaceAll(newText)
        file.write(fileText)
      }
                                 
    } 

println "---------------------------------------------------------------------------------------------"

- FIN -

No comments: