#!/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 服務器中的舊檔案,目前對于如何安全清除數千個檔案和檔案夾非常迷茫>。<
uj5u.com熱心網友回復:
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,最好先洗掉非目錄,然后(現在為空)目錄。或者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
}
}
注意——這還沒有經過全面測驗
注意 - 確保不要洗掉您開始搜索的頂級目錄!
uj5u.com熱心網友回復:
為什么要使用 Perl 來完成這么簡單的任務?
您可以使用簡單的 UNIXfind來完成此任務,如下所示:
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/432384.html
