删除目录中的所有文件,但保留目录?
答
更简单的方法是'不适用于perl'。
find /files/axis -mtime +30 -type f -exec rm {} \;
答
这会照你的要求去做。它使用opendir
/readdir
来列出目录。 stat
获取所有必要的信息,以及随后的-f _
和-M _
调用检查项目是否为文件且大于30天而不重复stat
调用。
use strict;
use warnings;
use 5.010;
use autodie;
no autodie 'unlink';
use File::Spec::Functions 'catfile';
use constant ROOT => '/path/to/root/directory';
STDOUT->autoflush;
opendir my ($dh), ROOT;
while (readdir $dh) {
my $fullname = catfile(ROOT, $_);
stat $fullname;
if (-f _ and -M _ > 30) {
unlink $fullname or warn qq<Unable to delete "$fullname": $!\n>;
}
}
如果你想删除文件下随时随地给定的目录,因为我已经开始相信,那么你需要File::Find
。整体结构与我的原始代码并无太大区别。
use strict;
use warnings;
use 5.010;
use autodie;
no autodie 'unlink';
use File::Spec::Functions qw/ canonpath catfile /;
use File::Find;
use constant ROOT => 'E:\Perl\source';
STDOUT->autoflush;
find(\&wanted, ROOT);
sub wanted {
my $fullname = canonpath($File::Find::name);
stat $fullname;
if (-f _ and -M _ < 3) {
unlink $fullname or warn qq<Unable to delete "$fullname": $!\n>;
}
}
答
对于跨平台兼容的Perl解决方案,我会推荐以下两个模块之一。
-
#!/usr/bin/env perl use strict; use warnings; use Path::Class; my $dir = dir('/Users/miller/devel'); for my $child ($dir->children) { next if $child->is_dir || (time - $child->stat->mtime) < 60 * 60 * 24 * 30; # unlink $child or die "Can't unlink $child: $!" print $child, "\n"; }
-
#!/usr/bin/env perl use strict; use warnings; use Path::Iterator::Rule; my $dir = '/foo/bar'; my @matches = Path::Iterator::Rule->new ->file ->mtime('<' . (time - 60 * 60 * 24 * 30)) ->max_depth(1) ->all($dir); print "$_\n" for @matches;
查看现有职位:http://stackoverflow.com/questions/25090951/perl-delete-all-files-在目录和这个要点:https://gist.github.com/johnhaitas/1507529 – 2014-10-18 08:45:25
写了一个解决方案,我'我认为你可能想要检查*中的所有文件并且在给定的目录下。是对的吗? – Borodin 2014-10-18 14:07:28