Ant FAQ: Ant replace task examples

Ant replace FAQ: Can you share some examples of the Ant replace task?

I've been sharing a lot of Ant tasks lately, and here's another example, this time some Ant replace task examples.

Ant replace task examples

The Ant build script lines shown below demonstrate how to issue a series of Ant replace commands to replace a token in the file with a variable you want to substitute for that token:

<!-- ant replace commands -->
<replace file="${temp.dir.web-inf}/applicationContext.xml" token="@db_url@" value="${db_url}" />
<replace file="${temp.dir.web-inf}/applicationContext.xml" token="@db_driver@" value="${db_driver}" />
<replace file="${temp.dir.web-inf}/applicationContext.xml" token="@db_username@" value="${db_username}" />
<replace file="${temp.dir.web-inf}/applicationContext.xml" token="@db_password@" value="${db_password}" />
<replace file="${temp.dir.web-inf}/applicationContext.xml" token="@initial_pool_size@" value="${initial_pool_size}" />
<replace file="${temp.dir.web-inf}/applicationContext.xml" token="@max_pool_size@" value="${max_pool_size}" />
<replace file="${temp.dir.web-inf}/managed-beans.xml" token="@nagios_config_dir@" value="${nagios_config_dir}" />
<replace file="${temp.dir.web-inf}/managed-beans.xml" token="@nagios_command_listener_server@" value="${nagios_command_listener_server}" />
<replace file="${temp.dir.web-inf}/managed-beans.xml" token="@nagios_command_listener_port@" value="${nagios_command_listener_port}" />
<replace file="${temp.dir.web-inf}/monitoring-managed-beans.xml" token="@nagios_status_filename@" value="${nagios_status_filename}" />
<replace file="${temp.dir.classes}/log4j.properties" token="@log4j_output_file@" value="${log4j_output_file}" />

Ant replace task - discussion

If you look at just one line of code -- like the Ant replace example shown below -- you can see that I'm simply looking for a token in the file (like @db_url@), and I'm replacing that token with the value of a variable (like ${db_url}). The variable can be defined earlier in your Ant script, or read in from a properties file (which is what I usually do).

<replace file="${temp.dir.web-inf}/applicationContext.xml" token="@db_url@" value="${db_url}" />

As in many of my recent Ant examples I'm just sharing this code, and I'm hoping the whole collection of examples will prove useful to you.