2011-12-26 107 views
-4

問題爲其Perl代碼是待開發的情況如下:重命名一組目錄和文件中的每個這些目錄

有一個包含了好目錄根目錄。每個子目錄都有一個文本文件。

我們需要進入根目錄的每個目錄,並首先重命名該目錄內的文件。然後,我們將需要返回,或上一個目錄,並用與其包含的文本文件名稱相同的名稱替換目錄名稱。

步驟:

  1. 打開每個目錄
  2. 重命名該目錄中的文本文件打開
  3. 進入上一層,併爲文本文件,其同名文件夾重命名本身含有
  4. 移動到根目錄中的下一個目錄
+1

打電話給我,當你在循環中操作時,你會爲所有文本文件指定相同的名字嗎?你的新名字是什麼? – run 2011-12-26 06:38:13

回答

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 $!; 

} 
+0

魔鬼是什麼?\/\「全是,呃? – tchrist 2011-12-28 13:56:22

+0

alrit ..'「\ /」'追加'/'目錄。當u構建絕對文件名,我們需要添加'「/」'到目錄,然後是文件名 例如:'目錄名($實例)''返回/ XYZ/abc' 和文件名會'file.txt' 那麼完整的文件將是'/ xyz/abc/file.txt' 如果你不添加'/它將會是'/ xyz/abcfile.txt'這是不正確的 – run 2011-12-29 04:22:36

+0

你不應該逃避斜槓,你不應該引用變量的方式,你這樣做。 – tchrist 2011-12-29 05:20:19

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; 
} 
+0

downvoter照顧解釋? – TLP 2011-12-26 15:58:04

2

可以使用File::Find模塊,它遍歷模塊中的目錄樹recursively.The 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);