Linux removing folders older than 1 year and more

2020-01-29 01:55发布

问题:

I'm writing an ant script to clean up an archive folder

Here's how I need to clean it up: I need to delete folders old than a certain amount of days AND has more than 3 files in it. So for example if a folder is 300 days old but only has 3 files than it will NOT be deleted.

I know I can ssh into the archive and do find -mtime +365 -exec rm -rf {} ;\ to delete files older than 1 year but I don't know how to account for the minimum of 3 files

I also know that find -type f | wc -l will list the number of files, but that doesn't really help in terms of scripting

Any ideas?

回答1:

ANT selectors enable you to customize the fileset to delete.

Try the following:

<target name="purge">

    <tstamp>
        <format property="touch.time" pattern="MM/dd/yyyy hh:mm aa" offset="-300" unit="day"/>
    </tstamp>

    <delete>
        <fileset dir="${src.dir}">
            <date datetime="${touch.time}" when="before"/>

            <scriptselector language="javascript"><![CDATA[
                if (file.getParentFile().list().length > 3) {
                    self.setSelected(true);
                }
                else {
                    self.setSelected(false);
                }
            ]]> </scriptselector>
        </fileset>
    </delete>
</target>