Ant to replace the file text that does not start with

advertisements

I want to make an ant target that can replace the content of a file (or more) that does not starts with a defined pattern. Is there a solution for this using ant and replaceregexp ? Or an alternative to this? Example:

  • I have file boo.txt that has the text: "this is boo".
  • Also I have the file foo.txt that has the text: "just foo".

I want to change the text for the foo.txt to: "this just foo"


Probably a case of cooking up a suitable regular expression with captures.

This one appears to work for the example you give.

<property name="prefix" value="this " />
<replaceregexp flags="s" match="^(${prefix})?(.*)" replace="${prefix}\2">
    <fileset dir="files" />
</replaceregexp>

  • The files are specified using a fileset - here all files in the files directory.
  • The prefix we want to optionally add is this, which is stored in a property, as we need to mention it in two places.
  • The flags="s" setting ensures that we treat the file as a single string for match purposes (rather than matching each line).
  • The regular expression looks for the prefix string in the file, and stores it in capture \1 - which is discarded.
  • The rest of the string is in capture \2.
  • Replace with the prefix string, followed by capture \2.

You might think of it as always adding the prefix, but after taking the prefix away if it's already there...except that the replaceregexp task will not write the file unless if differs from the existing.