Perl 删除目录中的所有文件,但保留该目录?

Perl 删除目录中的所有文件,但保留该目录?,perl,history,delete-file,Perl,History,Delete File,最简单的方法是: 删除给定目录/文件/轴中的所有文件(取消链接) 仅限于超过30天的文件 空目录应该保留(不要rmdir) 这将按您的要求执行。它使用opendir/readdir列出目录stat获取所有必要的信息,随后的-f和-M调用将检查项目是否为文件且是否超过30天,而无需重复stat调用 use strict; use warnings; use 5.010; use autodie; no autodie 'unlink'; use File::Spec::Functions 'c

最简单的方法是:

  • 删除给定目录/文件/轴中的所有文件(
    取消链接
  • 仅限于超过30天的文件
  • 空目录应该保留(不要
    rmdir

    • 这将按您的要求执行。它使用
      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>;
        }
      }
      

      更简单的方法是“不使用perl”

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

      对于跨平台兼容的Perl解决方案,我建议使用以下两个模块之一


    • 请参阅现有帖子:要点是:在编写了一个解决方案之后,我认为您可能需要检查给定目录中及其下的所有文件。是这样吗?
      find /files/axis -mtime +30 -type f -exec rm {} \;
      
      #!/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;