-4

perl代码要开发的问题如下:

有一个根目录,其中包含多个目录。每个子目录中都有一个文本文件。

我们需要进入根目录的每个目录,并首先重命名该目录中的文件。然后我们需要返回,或者上一个目录,并将目录名称替换为与它包含的文本文件相同的名称。

脚步:

  1. 打开每个目录
  2. 重命名打开的目录中的文本文件
  3. 上一层并将目录本身重命名为与其包含的文本文件相同的名称
  4. 移动到根目录中的下一个目录
4

3 回答 3

2

您可以使用File::Find模块,它递归地遍历目录树finddepth()。模块中的函数可用于此目的,它从目录树的底部向上执行后序遍历工作。

use File::Find;
my $DirName = 'path_of_dir' ;

sub rename_subdir
{
    #The path of the file/dir being visited.
    my $orignm = $File::Find::name;
    my $newnm = $orignm . '_rename';
    print "Renaming $orignm to $newnm\n";
    rename ($orignm, $newnm);
}

#For each file and sub directory in $Dirname, 'finddepth' calls
#the 'rename_subdir' subroutine recursively.
finddepth (\&rename_subdir, $DirName);
于 2011-12-26T17:14:57.060 回答
0

您还没有提到如何存储将用于重命名的文件名,所以我假设它是一种通用类型的更改,例如“file_x”->“file_x_foo”。你必须自己定义。

该脚本将尝试重命名目录中的所有文件,假设目录中唯一的常规文件是目标文件。如果目录中有更多文件,则需要提供一种识别该文件的方法。

该脚本采用一个可选参数,即根目录。

这是示例代码,未经测试,但它应该可以工作。

use strict;
use warnings;
use autodie;
use File::Copy;

my $rootdir = shift || "/rootdir";
opendir my $dh, $rootdir;
chdir $rootdir;
my @dirlist = grep -d, readdir $dh;   
for my $dir (@dirlist) {
    next if $dir =~ /^\.\.?$/;
    chdir $dir;
    for my $org (grep -f, glob "*.txt") { # identify target file
        my $new = $org;
        $new .= "_foo";   # change file name, edit here!
        move $org, $new;
    }
    chdir "..";
    move $dir, $new;
}
于 2011-12-26T09:21:22.260 回答
0

嗨,我正在尝试概述您的想法

#!/usr/bin/perl
use strict;
use File::Find;
use Data::Dumper;
use File::Basename;
my $path = 'your root directory';
my @instance_list;
find (sub { my $str = $_;
        if($str =~ m/.txt$/g) {                             
            push @instance_list, $File::Find::name if (-e $File::Find::name); 
        } 
      }, $path);
print Dumper(@instance_list);




for my $instance (@instance_list) {
  my $newname = 'newEntry';
  my $filename = basename( $instance );
  #rename the file 1st,
  my $newFileName = dirname( $instance ) .'/'. $filename.$newname.'.txt'
;

  rename($instance, $newFileName) or die $!;
  #rename the directory
  my $newDirName = dirname(dirname( $instance ) ).'/'. $newname;

   rename(dirname($instance), $newDirName) or die $!;

}
于 2011-12-26T06:42:39.473 回答