Replacing all tokens based on properties file with ANT

With the replace task by itself I missed the @ delimiters around tokens so I came up with the following solution. You can use any ant property in the template file

<project name="replace" default="replace">

<property file="build.properties" />
<target name="replace">

    <!-- create temp file with properties -->
    <tempfile property="temp.replace" suffix=".properties"/>
    <echoproperties destfile="${temp.replace}" />
    <!-- replace name=value with @name@=value -->
    <replaceregexp file="${temp.replace}" match="([^=]*)=" replace="@\1@=" byline="true" />

    <!-- copy template and replace properties -->
    <copy file="template.txt" tofile="replaced.txt" />
    <replace file="replaced.txt" replacefilterfile="${temp.replace}" />

</target>

with a template

ANT home @ant.home@
ANT version @ant.java.version@
server name @server.name@ ip @server.ip@

this results in

ANT home /usr/share/ant
ANT version 1.7
server name dummy_server_name ip 127.0.0.1

You can specify the properties file from which to read the list of tokens for the 'replace' task using replacefilterfile:

<replace file="input.txt" replacefilterfile="properties.txt"/>

Similarly, in a filter chain, you can use 'replacetokens' propertyfile:

This will treat each properties file entry in sample.properties as a token/key pair:

<loadfile srcfile="${src.file}" property="${src.file.replaced}">
  <filterchain>
    <filterreader classname="org.apache.tools.ant.filters.ReplaceTokens">
      <param type="propertiesfile" value="sample.properties"/>
    </filterreader>
  </filterchain>
</loadfile>

Tags:

Ant

Tokenize