Replace a token with a variable using ANT

You may be looking for the following:

How do you replace a string in a file using a property in ANT?

How do you replace a string using a variable in ANT?


There are a few ways to do this. First question is what do you mean by a variable? Do you mean a variable set in a property file like the following?

prompt> ls -l
-rw-r--r--@ 1 nicholasdunbar staff 2245 Nov 15 13:42 dev2.properties

The contents of dev2.properties being something like the following:

prompt> cat dev2.properties
crontabPath=/some/dir/

or do you mean a variable set in a property in your build file like the following?



First we will talk about how to do it with the property file and then with the property tag/task.

Example 1 property file:

So lets say we have the following files:

prompt> ls -l
-rw-r--r--@ 1 nicholasdunbar staff 2245 Nov 15 13:42 dev2.properties
-rw-r--r-- 1 nicholasdunbar staff 369 Nov 13 18:39 crontab
prompt> cat dev2.properties
crontabPath=/some/dir/
prompt> cat crontab
00 00 * * * echo '25 hour record written by the crontab:' > @cronPath@crontab.log;

If we want to replace @cronPath@ in the file crontab with '/some/dir/' from dev2.properties we would use the following ANT task:


So we have generated a file called crontabTest.txt and replaced the tokens with our "variable" as we can see in the following:

prompt> cat crontabText.txt
00 00 * * * echo '25 hour record written by the crontab:' > /some/dir/crontab.log;

Example 2 using the property task to replace a token with a variable:


So if we were to look in the file crontabTest.txt we would see the following:

prompt> cat crontabText.txt
00 00 * * * echo '25 hour record written by the crontab:' > /some/dir/crontab.log;

As you can see the token has successfully been replaced. Thank you for reading. Please, leave a comment if this helped you or if you have a question.

comments powered by Disqus