How to strip the basedir from an absolute path to get a relative path?

blackicecube picture blackicecube · Jan 8, 2010 · Viewed 34.4k times · Source

In the build.xml of my project I have a property defined:

<property name="somedir.dir" location="my_project/some_dir"/>

The value of ${somedir.dir} will be an absolute path: /home/myuser/my_project/some_dir.

What I need is just the relative path ./my_project/some_dir without the ${basedir} value /home/myuser. How can I achieve this using Ant?

So far I found a solution by converting the property to a path and then use "pathconvert", but I don't think this is a nice solution:

<path id="temp.path">
    <pathelement location="${somedir.dir}" />
</path>
<pathconvert property="relative.dir" refid="temp.path">
    <globmapper from="${basedir}/*" to="./*" />
</pathconvert>

Any other (more elegant) suggestions?

Answer

martin clayton picture martin clayton · Jan 21, 2011

Since Ant 1.8.0 you can use the relative attribute of the Ant property task for this.

For example:

<property name="somedir.dir" location="my_project/some_dir"/>
<echo message="${somedir.dir}" />

<property name="somedir.rel" value="${somedir.dir}" relative="yes" />
<echo message="${somedir.rel}" />

Leads to:

 [echo] /home/.../stack_overflow/ant/my_project/some_dir
 [echo] my_project/some_dir