Replacing all tokens based on properties file with ANT

心已入冬 提交于 2019-11-29 05:59:45

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>

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
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!