重命名一组目录和每个目录中的文件

时间:2011-12-26 05:20:01

标签: perl renaming

开发perl代码的问题如下:

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

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

步骤:

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

3 个答案:

答案 0 :(得分: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);

答案 1 :(得分: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 $!;

}

答案 2 :(得分: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;
}
相关问题