David R. Heffelfinger

Bookmark and Share
Thursday Jul 30, 2009
Bookmark and Share

Groovy Script to Find and Replace Text


Lately I've been reading a bit about Groovy .Today I had to do a search and replace across several files, and decided to put my newly found Groovy knowledge to use. I wrote a simple script to search all files with a given extension, and search and replace a String inside each file.

I know this can be accomplished as a one liner, but I don't want to try and remember the syntax every time I need to do it. Also, there may be a "groovier" way to do it, being primarily a Java developer I don't really know (and quite frankly, I don't care that much, it works). Without further ado, here is the script for your copying and pasting pleasure:

 

#!/usr/bin/env groovy

def currentDir = new File(".");

def backupFile;
def fileText;

//Replace the contents of the list below with the
//extensions to search for
def exts = [".txt", ".foo"]

//Replace the value of srcExp to a String or regular expression
//to search for.
def srcExp = "dummy"

//Replace the value of replaceText with the value new value to
//replace srcExp
def replaceText = "awesome"

currentDir.eachFileRecurse(
{file ->
for (ext in exts){
if (file.name.endsWith(ext)) {
fileText = file.text;
backupFile = new File(file.path + ".bak");
backupFile.write(fileText);
fileText = fileText.replaceAll(srcExp, replaceText)
file.write(fileText);
}
}
}
)



I could have made it a bit "fancier", taking command line parameters and what not, but this is just a simple script I solved to have a simple immediate problem I was having. With a couple of simple changes it can be adapted to search different file types, search and replace strings. Enjoy.

Bookmark and Share
Ensode Technology, LLC
Ensode
Technology, LLC

Calendar


Feeds

Search

Links

Navigation