2012-02-29 144 views
3

我正在嘗試編寫一個Perl腳本,它讀取目錄中的所有文本文件,並將除第一個以外的所有行寫入單獨的文件。如果有3個文件,我希望腳本讀取所有這3個文件,並使用除第一個以外的相同行寫入3個新文件。這是我寫的,但是當我嘗試運行這個腳本時,它沒有錯誤地執行正常,但沒有做它應該做的工作。有人可以看看它嗎?從目錄中的所有文本文件中刪除第一行的腳本

opendir (DIR, "dir\\") or die "$!"; 
my @files = grep {/*?\.txt/} readdir DIR; 
close DIR; 
my $count=0; 
my $lc; 
foreach my $file (@files) { 
    $count++; 
    open(FH,"dir\\$file") or die "$!"; 
    $str="dir\\example_".$count.".txt"; 
    open(FH2,">$str"); 
    $lc=0; 
    while($line = <FH>){ 
     if($lc!=0){ 
      print FH2 $line; 
     } 
     $lc++; 
    } 
    close(FH); 
    close(FH2); 
} 

而第二個文件不存在,它應該由腳本創建。

+1

它適用於我,但我不得不在第二行中引用'*'。你真的有一個名爲'dir'的目錄,並且是你的路徑分隔符'\\'? – 2012-03-01 01:18:52

+1

@ EmilioSilva-謝謝,那就是問題所在。 – questions 2012-03-01 03:45:11

回答

1

嘗試改變這些線

opendir (DIR, "dir\\") or die "$!"; 
... 
close DIR; 

opendir (DIR, "dir") or die "$!"; 
... 
closedir DIR; 

我試着在本地運行你的代碼,我唯一的兩個問題是目錄名稱包含尾部斜槓並試圖在dirhandle上使用文件句柄close()函數。

+1

非常感謝,另一個問題沒有引用*。 – questions 2012-03-01 03:46:35

1

如果你有文件的列表...走出去的範圍時

foreach my $file (@files) { 
    open my $infile , '<' , "dir/$file" or die "$!" ; 
    open my $outfile , '>' , "dir/example_" . ++${counter} . '.txt' or die "$!" ; 
    <$infile>; # Skip first line. 
    while(<$infile>) { 
    print $outfile $_ ; 
    } 
} 

詞法文件句柄將被自動關閉。

+1

'print $ outfile <$infile>'。 – TLP 2012-03-01 00:13:51

0

不知道爲什麼你正在使用$這裏算,因爲那將只是把像文件的列表:

01.txt 
bob.txt 
alice.txt 
02.txt 

到:

01_1.txt 
bob_2.txt 
alice_3.txt 
02_4.txt 

請記住,@files ISN不會被排序,所以它會按文件在目錄表中的順序返回。如果要刪除並重新創建文件01.txt,將它移動到列表中,重新排序整個集的結尾:

bob_1.txt 
alice_2.txt 
02_3.txt 
01_4.txt 

因爲那是你原來的沒有真正的一部分問題,這不正是你要求做:

#!/usr/bin/perl 
while(<*.txt>) { # for every file in the *.txt glob from the current directory 
    open(IN, $_) or die ("Cannot open $_: $!"); # open file for reading 
    my @in = <IN>; # read the contents into an array 
    close(IN); # close the file handle 
    shift @in; # remove the first element from the array 

    open(OUT, ">$_.new") or die ("Cannot open $_.new: $!"); # open file for writing 
    print OUT @in; # write the contents of the array to the file 
    close(OUT); # close the file handle 
} 
相關問題