首页 > 解决方案 > 如何更改我的脚本以列出子文件夹中的文件?

问题描述

我想更改我的脚本以列出子文件夹中的文件。假设我选择文件夹 /lib64 y 也想搜索子文件夹谢谢您的帮助。

我需要帮助,不仅要列出给定的文件夹,还要列出子文件夹

在我的脚本下面,工作没有任何问题......

#!/usr/bin/perl -w

system("clear");
my $dev;
my $ino;
my $mode;
my $nlink;
my $uid;
my $gid;
my $rdev;
my $size;
my $atime;
my $mtime;
my $ctime;
my $blksize;
my $blocks;
my $perm;
my $tmp1;
my $tmp2;
clear;

print " \n";
print "Please enter the Directory you want to list : ";
my $dir = <STDIN>;
chomp $dir;
print "Directory selected is ------------> $dir | \n \n";

print "Please enter the minimum size (in bytes) of files you want to list 
: ";
my $sz = <STDIN>;
chomp $sz;
print "Minimal size of files (in bytes)-----------------> $sz | \n \n";
print "...........Please wait, preparing the file listing....... \n \n";

sleep 6;

opendir (DIR, $dir ) or die "Cannot open $dir";

while (my $file = readdir(DIR)) {

($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
     $atime,$mtime,$ctime,$blksize,$blocks) = stat("$dir/$file");


$perm = sprintf("%04o", $mode & 07777);
$tmp1 = int(($size/$sz));
$tmp2 = length($file);


if (($tmp1 > $tmp2) && ($perm =~ /.[^5410]../)) {

    print "List of files in --> $dir | ";
    print("File Name: -$file- | Size in bytes -$size- \n");
}
}

closedir(DIR);

标签: listfileperl

解决方案


这是使用Path::Iterator::Rule递归迭代的示例。此外,File::stat是一个更简单的 stat 字段接口。

use strict;
use warnings;
use Path::Iterator::Rule;
use File::Basename;
use File::stat;

print "Please enter the Directory you want to list : ";
chomp(my $dir = readline *STDIN);
print "Please enter the minimum size (in bytes) of files you want to list : ";
chomp(my $sz = readline *STDIN);

my $rule = Path::Iterator::Rule->new->not_dir->size(">=$sz");
my $next = $rule->iter($dir);
while (defined(my $file = $next->())) {
  my $stat = stat $file or die "Failed to stat $file: $!";
  my $mode = $stat->mode;
  my $size = $stat->size;
  my $basename = basename $file;
  ...
}

推荐阅读