Search This Blog

Thursday, May 29, 2014

Replace characters Using ANT

There is an inbuilt task given in ant library called 'replaceregexp'. This task is used to check about a specific pattern i.e. a regular expression and replace them with a different pattern in a single file or set of files.

Replace in a set of files

<replaceregexp match="test" replace="replacedTest" flags="gm" byline="false">
            <fileset dir="${sf.srcdir}" includes="*.txt" />
</replaceregexp>
The above task will look at all the files ending with extension 'txt' in the source directory given as 'sf.srcdir' in the properties file. In all those files, it tries to find the pattern 'test' and replaces with pattern 'replacedTest'



The flags indicate the options for regular expression match;
  • g : Global replacement. Replace all occurrences found
  • i : Case Insensitive. Do not consider case in the match
  • m : Multiple line. Treat the string as multiple lines of input, using "^" and "quot; as the start or end of any line, respectively, rather than start or end of string.
  • s : Singleline. Treat the string as a single line of input, using "." to match any character, including a newline, which normally, it would not match.
'byline' option indicates to process the file(s) one line at a time, executing the replacement on one line at a time (true/false). This is useful if you want to only replace the first occurrence of a regular expression on each line, which is not easy to do when processing the file as a whole

Replace in a single file

If it is required to check in a single file, then instead of fileset use file attribute.
<replaceregexp match="\s*<\w*>unfiled\$\w*</\w*>" replace="" flags="gm" byline="false" file='${sf.srcdir}/package.xml'/>
More on this can be found here.

No comments:

Post a Comment