How to extract part of a filename with Apache Ant?
I want to extract the version number from a file name generated outside of my Ant script.
An external build tool (PDE build) creates a file of the form artifactid-1.2.3.201101010101.jar
in a well-known directory, but I can not tell the versioning information beforehand. I need to extract the version part (1.2.3.201101010101
) from that file name into an Ant property for further processing, e.g. variable substitution.
Usi开发者_如何学Gong ant-contrib is acceptable, however I have not found a way to extract this information.
Here's a solution using the ant-contrib PropertyRegex task.
- Get the filename into a path.
- Convert the path to a property.
- PropertyRegex the property (ant-contrib).
You could avoid ant-contrib by writing the property value to a temporary file and then using loadfile with a filterchain to extract the artifact id from it. See this answer for an example.
<project default="get-revision-number">
<taskdef resource="net/sf/antcontrib/antcontrib.properties">
<classpath>
<pathelement location="c:/lib/ant-contrib/ant-contrib-1.0b3.jar"/>
</classpath>
</taskdef>
<target name="get-revision-number">
<path id="artifact.id.path">
<fileset dir=".">
<include name="artifactid-*.jar"/>
</fileset>
</path>
<property name="artifact.id.file" refid="artifact.id.path"/>
<echo message="artifact.id.file: ${artifact.id.file}"/>
<propertyregex property="artifact.id" input="${artifact.id.file}" regexp=".*artifactid-(.*).jar" select="\1" />
<echo message="artifact.id: ${artifact.id}"/>
</target>
</project>
Output
$ ant
Buildfile: C:\tmp\build.xml
get-revision-number:
[echo] artifact.id.file: C:\tmp\artifactid-1.2.3.201101010101.jar
[echo] artifact.id: 1.2.3.201101010101
BUILD SUCCESSFUL
Total time: 0 seconds
A straight solution with Ant addon Flaka :
<project name="demo" xmlns:fl="antlib:it.haefelinger.flaka">
<property name="filename" value="artifactid-1.2.3.201101010101.jar"/>
<!-- simple echo -->
<fl:echo>Version => #{replace('${filename}', '$1', '.+-(.+).jar')}</fl:echo>
<!-- create property for further processing -->
<fl:let>fileversion := replace('${filename}', '$1', '.+-(.+).jar')</fl:let>
<echo>$${fileversion} => ${fileversion}</echo>
</project>
output
Buildfile: /home/rosebud/workspace/ant/demo.xml
[fl:echo] Version => 1.2.3.201101010101
[echo] ${fileversion} => 1.2.3.201101010101
BUILD SUCCESSFUL
精彩评论