2013-07-11 219 views
-1

我正在研究一個腳本,它將讀取文件,並根據文件內容重新命名文件。如何遍歷目錄和子目錄中的所有文件

問題,我現在面臨:

1日,我無法讀取文件,該文件是在子目錄中。 第二我想重命名文件,但出現錯誤。

這裏是我的代碼:

   Folder Structur : 
         Logs 
        ///\ 
        a b c d 
       /\ \ 
        e file file 

其中A,B,C,d,e爲DIR 文件,文件是txt文件

#!/usr/bin/perl 
use strict; 
use warnings; 
use File::Copy::Recursive; 
use Cwd; 
my $file; 
my (@FILES,@File_01); 
my ($dir_01,$dir_02); 
my $new_file="Kernel.txt"; 
chdir('C:\\abd\\efg'); 
$dir_01 = getcwd; 
opendir(DIR_01, $dir_01); 
@FILES=readdir(DIR_01); 
close(DIR_01); 
foreach $dir_02 (@FILES) 
{ 
    opendir (DIR_02, "$dir_01"."/"."$dir_02") ; 
    @File_01=readdir(DIR_02); 
    close(DIR_02); 
    foreach $file (@File_01) 
    { 
     open(FH,"<","$dir_01/$dir_02/$file") or die "can not open the file $!\n"; 
     while(my $lines = <FH>) 
     { 
      if($lines=~ m/Linux kernel Version/i || $lines=~ m/USB_STATE=DISCONNECTED/gi) 
      { 
      #print "\t$lines\n\n"; 
      rename($file,$new_file) or die "can not change the name"; 
      } 
     } 
    } 
} 
+0

你的意思是「無法打開」重命名?你有錯誤信息嗎?哪一個? – Matteo

+1

[如何遍歷目錄中的所有文件;如果它有子目錄,我想遍歷子目錄中的文件](http://stackoverflow.com/questions/9600395/how-to-traverse-all-the-files-in-a-directory-if-it-has -subdirectories -i-want-t) – innaM

回答

0
rename($file,$new_file) 

不會工作,因爲你沒有指定路徑

rename("$dir_01/$dir_02/$file", $new_file) 

但也像這樣匹配的任何文件將在當前目錄中重命名爲Kernel.txt。這是預期的行爲?

+0

是的,這是預期的行爲。先生那麼我的第二個問題,我的意思是我將如何閱讀子目錄文件:( – Maverick

+0

@Maverick你應該是一個更具體一點:這是實際的問題?一個錯誤?什麼都沒有發生?你有沒有嘗試寫的內容@ FILES'和'@ File_01'到控制檯? – Matteo

+0

@ Matteo我沒有得到任何錯誤,它是所有的內容。 – Maverick

0

嘗試模塊文件::接下來 例如:

my $iter = File::Next::files($some_dir); 
while(my $fn = $iter->()) { 
    my $rename = 0; 
    open(my $FILE,'<',$fn); 
    while(my $line = <$FILE>) { 
     if($lines=~ m/Linux kernel Version/i || $lines=~ m/USB_STATE=DISCONNECTED/gi) 
      $rename = 1; 
      last; 
     } 
    } 
    close($FILE); 
    if($rename) { 
     rename($fn,$new_file) or die "can not change the name"; 
    } 
} 

也許你不能重命名,因爲重命名打開文件 嘗試後關閉打開的文件

相關問題