2016-01-20 87 views
-3

我有這個代碼工作,但這只是一個具有特定名稱的文件,我怎麼能讓它執行當前文件夾中的所有.vb文件並輸出文件名加_1在後面Perl多個文件讀取替換字符串,寫入多個文件

#!/usr/bin/perl 
use strict; 
use warnings; 

open my $fhIn, '<', 'file.vb'   or die $!; 
open my $fhOut, '>', 'file_1.vb'  or die $!; 

while (<$fhIn>) { 
    print $fhOut "'01/20/2016 Added \ngpFrmPosition = Me.Location\n" if /MessageBox/ and !/'/; 

    print $fhOut $_; 
} 

    enter code here 

close $fhOut; 
close $fhIn; 
+2

'在此處輸入代碼 - 很好的接觸。 [readdir](http://perldoc.perl.org/functions/readdir.html)怎麼樣? (它看起來並不像你自己花費很多精力研究和/或解決這個問題。) –

+0

不清楚你正在努力的部分,但[this](http://stackoverflow.com/questions/22566/how-do-i-read-in-the-contents-of-a-directory-in-perl/22573)會讓你有97%的選擇。 –

+1

@MattJacob:'在此處輸入代碼'是Stack Overflow頁面寫入的內容,如果您嘗試在沒有選擇任何內容的情況下將您的帖子標記爲代碼 – Borodin

回答

2

我可能會這樣做。 (假定腳本與.vb文件在同一目錄中運行)。

#!/usr/bin/perl 
use strict; 
use warnings; 

# script running in same directory as the .vb files 

for my $file (glob "*.vb") { 

    my $outfile = $file =~ s/(?=\.vb$)/_1/r; 
    print "$file $outfile\n"; # DEBUG 

    # open input and output files 

    # do the while loop 
} 

循環中的print語句用於調試目的 - 查看是否正確創建新文件名。當你滿意你已經得到你想要的文件時,你可以將其刪除或註釋掉。

更新:將glob放入for循環而不是將其讀入數組。