Using ant, find files matching a regular expressio

2019-07-14 15:36发布

问题:

I have a directory containing 2 files:

abc_2010-14-12.log

abcdef.log

I want to search for a substring in the 1st file. But i dont know the exact file name as it has timestamp appended to it. I think i will have to use regular expression in the file name.

回答1:

First you must identify the file. You may be able to do that using a normal fileset include:

<fileset dir="." id="the.file" includes="abc_????-??-??.log" />

If that might give you a false positive on something like 'abc_XXXX-YY-ZZ.log', then you can use a filename selector, which has more powerful matching than the 'glob' wildcarding available in include and exclude rules:

<fileset dir="." id="the.file">
    <filename regex=".*_[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9].log"/>
</fileset>

You might be able to restrict further, assuming (based on your example) YYYY-DD-MM:

<filename regex=".*_20[01][0-9]-[0-3][0-9]-[01][0-9].log"/>

These will give you a fileset that matches, hopefully just the one file.

If you have more than one matching file present - say several days' log files - you'll need to decide which one you want. You could make use of the tstamp task to exactly specify the filename based on the current date, rather than using a pattern match or glob. This example gets the file with yesterday's date, matching your format:

<tstamp>
    <format property="file.date" pattern="yyyy-dd-MM"
            offset="-1" unit="day"/>
</tstamp>
<fileset dir="." id="the.file" includes="abc_${file.date}.log" />

Once you have identified the file, you can use the resourcecontains condition to set a property if the file matches - in this case we search for 'look for me':

<condition property="file.matches">
    <resourcecontains refid="the.file" substring="look for me" />
</condition>


标签: ant