ANT replacing strings in specified files using file with properties

17,185

Solution 1

try this:

<copy file="input.txt" tofile="output.txt">
   <filterchain>
   <replaceregex pattern="\$\{" replace="{" />
   <filterreader classname="org.apache.tools.ant.filters.ReplaceTokens">
        <param type="propertiesfile" value="properties.txt"/>
        <param type="tokenchar" name="begintoken" value="{"/>
        <param type="tokenchar" name="endtoken" value="}"/>
    </filterreader>
    </filterchain>
</copy>

Founded here: Ant replace token from properties file

Solution 2

In the following Ant script, replace the src-root property with the root directory containing the tokenized files:

<project name="ant-replace-tokens-with-copy-task" default="run">
    <target name="run">
        <!-- The <copy> task cannot "self-copy" files. So, for each -->
        <!-- matched file we'll have <copy> read the file, replace the -->
        <!-- tokens, and write the result to a temporary file. Then, we'll -->
        <!-- use the <move> task to replace the original files with the -->
        <!-- modified files. -->
        <property name="src-root" location="src"/>
        <property name="filtered-file.extension" value="*.filtered-file"/>

        <copy todir="${src-root}">
            <fileset dir="${src-root}">
                <include name="**/*.html"/>
                <include name="**/*.php"/>
            </fileset>
            <globmapper from="*" to="${filtered-file.extension}"/>
            <filterchain>
                <filterreader classname="org.apache.tools.ant.filters.ReplaceTokens">
                    <param type="propertiesfile" value="dev.properties"/>
                </filterreader>
            </filterchain>
        </copy>

        <move todir="${src-root}">
            <fileset dir="${src-root}" includes="**"/>
            <globmapper from="${filtered-file.extension}" to="*"/>
        </move>
    </target>
</project>

Solution 3

You specified that you do not want to edit your build script so this answer does not qualify but may still be useful to other readers.

If you were willing to edit your target file to use the format ${test.url} instead of [[test.url]] then ExpandProperites would be an excellent choice.

Share:
17,185
Cezary Tomczyk
Author by

Cezary Tomczyk

Updated on June 05, 2022

Comments

  • Cezary Tomczyk
    Cezary Tomczyk almost 2 years

    I have a properties in file dev.properties and they look like this:

    test.url=https://www.example.com/
    [...]
    

    and in project files there is a token [[test.url]] which I want to replace by https://www.example.com/. I just want to define all tokens in dev.properties and use them in build script, but without modifying build script and I want to replace those tokens in a specified files like *.php, *.html, etc.

    Can someone give me a suggestions how to do it? Thanks.