Introduction
At work, I was asked to write a command line utility program that will open a text file, search for a list of strings, and replace them with a list of new strings. The catch is, the program has to work on all platforms within my company (mostly, NT, Win2K, and AIX ). Since I am not familiar with Perl or other scripting languages, Java seemed to be my only choice.
TextRep, the java class I wrote for this purpose, first opens the input file and makes a backup copy of it. Then it starts to search and replace the strings specified by the user. Here are some examples on how to use this little program:
java TextRep c:\temp\test1.txt "Hello, world" "Hello, java world"
java TextRep c:\temp\test1.txt "Hello, java world" "Hello, world"
java TextRep c:\temp\test2.txt "server" "client"
The first command replaces all instances of the string "Hello, world" in file c:\temp\test1.txt with the string "Hello, java world". The second command will undo the changes made by the first command. The third command will replace all instances of the string "server" in file c:\temp\test2.txt with the string "client". If you want to replace the strings "word1", "word2", "word3", ..., with the strings "replace1", "replace2", "replace3", ..., respectively, in file mytest.txt, all you need to do is create a file, say mystrings.txt, containing the following lines:
word1
replace1
word2
replace2
word3
replace3
...
and run the following command:
java TextRep mytest.txt mystrings.txt
The source code included with this article is straightforward (with comments), but apparently not the most efficient Java code. You can probably find other free programs to do the same thing (or more) on multiple platforms. I hope someone will find my program useful. Thanks for reading.