David R. Heffelfinger

  Ensode Technology, LLC

 
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.

 
 
 
 
Comments:

Post a Comment:
Comments are closed for this entry.
 

« November 2024
SunMonTueWedThuFriSat
     
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
       
Today

 
© David R. Heffelfinger