2014-10-18 217 views
-3

什么是最简单的方法:删除目录中的所有文件,但保留目录?

  • 删除指定目录/文件/轴的所有文件(unlink
  • 只有30天
  • 旧文件的空目录应保持(不rmdir
+0

查看现有职位:http://stackoverflow.com/questions/25090951/perl-delete-all-files-在目录和这个要点:https://gist.github.com/johnhaitas/1507529 – 2014-10-18 08:45:25

+0

写了一个解决方案,我'我认为你可能想要检查*中的所有文件并且在给定的目录下。是对的吗? – Borodin 2014-10-18 14:07:28

回答

1

更简单的方法是'不适用于perl'。

find /files/axis -mtime +30 -type f -exec rm {} \; 
2

这会照你的要求去做。它使用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>; 
    } 
} 
0

对于跨平台兼容的Perl解决方案,我会推荐以下两个模块之一。

  1. Path::Class

    #!/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"; 
    } 
    
  2. Path::Iterator::Rule

    #!/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; 
    
相关问题