删除指定目录中的文件和文件夹

deleting files and folders in a specified directory

#!/usr/bin/perl

# purge backups older than 210 days

use strict;
use warnings;

use File::Find::Rule;
use File::Path 'rmtree'; # listed directory has files and folders

# to delete files and folders in the specified directory age > 210 days

my $dir = '/volume1/Backup01/*/Archived_files/';
my $days = 210;

# Do i need to input something like @folder = File::Path *** ??

my @files = File::Find::Rule->file()
                            ->maxdepth(1) # maxdepth(0) will allow me to delete files in subdirectories as well?
                            ->in($dir)

# How can I make a for loop to look for folders whose -M > 210 and allow me to delete?
                            
for my $file (@files){
    if (-M $file > 210){
        unlink $file or warn $!;
    }
}

包含我需要的评论...后台正在清除 NAS 服务器中的旧文件,目前完全不知道如何安全地清除几千个文件和文件夹 >.<

use warnings;
use strict;
use feature 'say';

use File::Find::Rule;    
use FindBin qw($RealBin);

my $dir = shift // $RealBin;   # start from this directory

my @old_entries = File::Find::Rule -> new 
    -> exec( sub { -M $_[2] > 210 } ) 
    -> in($dir); 

say for @old_entries; 

这会递归地找到所有早于 210 天的条目(文件和目录)。

现在浏览列表并删除。可以再次使用 -X filetests (-d) 来识别目录,最好先删除 non-directories 然后再删除(现在是空的)目录。或者按预期使用 rmtree 并跳过那些目录中的文件。


例如,

if ($old_entries[0] eq $dir) { 
    say "Remove from this list the top-level dir itself, $old_entries[0]";
    shift @old_entries;
}

my $del_dir;

for my $entry (@old_entries) {
    if (-d $entry) {
        $del_dir = $entry;
        say "remove $entry";  # rmtree
    }    
    # Skip files other than the ones at the top level
    elsif ($del_dir and $entry =~ /^$del_dir/) {
        say "\tskip $entry";  # its directory is removed
    }
    else { 
        say "Remove top-level file: $entry";  # unlink
    }
}

注意 -- 这还没有完全测试

注意 -- 确保不要删除您开始搜索的top-level目录!

为什么要使用 Perl 来完成如此简单的任务?
您可以使用简单的 UNIX find 来完成此任务,如您在此处所见:

find ./ -mtime +210 -delete

如果这不起作用(某些 find 版本没有 -delete 开关),您仍然可以使用以下内容:

find ./ -mtime +210 -exec rm -rf {} \;

如果您不想进入子目录,可以使用 maxdepth 参数:

find ./ -maxdepth 1 -mtime +210 -delete

您也可能只需要搜索文件,您可能还需要指定这些文件:

find ./ -type f -mtime +210 -delete