Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ant: Find the path of a file in a directory

Tags:

file

find

path

ant

I want to find the path of a file in a directory (similar to unix 'find' command or the 'which' command, but I need it to work platform-independent) and save it as a property.

Tried to use the whichresource ant task, but it doesn't do the trick (I think it's only good for looking inside jar files).

I would prefer if it would be pure ant and not to write my own task or use a 3rd-party extension.

Notice that there might be several instances of a file by that name in the path - I want it to only return the first instance (or at least I want to be able to choose only one).

Any suggestions?

like image 245
yonix Avatar asked Dec 20 '11 12:12

yonix


2 Answers

One possibility is to use the first resource selector. For example to find a file called a.jar somewhere under directory jars:

<first id="first">
    <fileset dir="jars" includes="**/a.jar" />
</first>
<echo message="${toString:first}" />

If there are no matching files nothing will be echoed, otherwise you'll get the path to the first match.

like image 178
martin clayton Avatar answered Oct 14 '22 16:10

martin clayton


Here is an example which selects the first matching file. The logic is as follows:

  • find all matches using a fileset.
  • using pathconvert, store the result in a property, separating each matching file with line separator.
  • use a head filter to match the first matching file.

The functionality is encapsulated in a macrodef for reusability.

<project default="test">

  <target name="test">
    <find dir="test" name="*" property="match.1"/>
    <echo message="found: ${match.1}"/>
    <find dir="test" name="*.html" property="match.2"/>
    <echo message="found: ${match.2}"/>
  </target>

  <macrodef name="find">
    <attribute name="dir"/>
    <attribute name="name"/>
    <attribute name="property"/>
    <sequential>
      <pathconvert property="@{property}.matches" pathsep="${line.separator}">
        <fileset dir="@{dir}">
          <include name="@{name}"/>
        </fileset>
      </pathconvert>
      <loadresource property="@{property}">
        <string value="${@{property}.matches}"/>
        <filterchain>
          <headfilter lines="1"/>
        </filterchain>
      </loadresource>
    </sequential>
  </macrodef>

</project>
like image 33
sudocode Avatar answered Oct 14 '22 15:10

sudocode