Cezary Tomczyk
Cezary Tomczyk

Reputation: 584

ANT replacing strings in specified files using file with properties

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.

Upvotes: 4

Views: 19395

Answers (3)

ryszardPL
ryszardPL

Reputation: 41

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

Upvotes: 4

PeterVermont
PeterVermont

Reputation: 2002

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.

Upvotes: 1

Chad Nouis
Chad Nouis

Reputation: 7041

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>

Upvotes: 1

Related Questions