2009-05-18 133 views
0

我編寫了一個腳本,用於讀取目錄中的每個文件,執行某些操作並將每個輸入文件的結果輸出到兩個不同的文件,例如, 「outfile1.txt」和「outfile2.txt」。我希望能夠給我生成的文件鏈接到原有的,所以我怎麼能添加輸入文件名(infile.txt)對獲得的文件名,拿到這樣的事情:Perl:將輸入文件名添加到輸出文件名

infile1_outfile1.txt,infile1_outfile2.txt

infile2_outfile1.txt,infile2_outfile2.txt

infile3_outfile1.txt,infile3_outfile2.txt ...?

感謝您的幫助!

回答

6

使用替代從輸入文件名刪除名爲「.txt」。 使用字符串連接建立自己的輸出文件名:

my $infile = 'infile1.txt'; 

my $prefix = $infile; 
$prefix =~ s/\.txt//; # remove the '.txt', notice the '\' before the dot 

# concatenate the prefix and the output filenames 
my $outfile1 = $prefix."_outfile1.txt"; 
my $outfile2 = $prefix."_outfile2.txt"; 
0

簡單的字符串連接應該在這裏工作,或旁觀CPAN一個合適的模塊

0

如果我理解正確的話,你在尋找這樣的事情?

use strict; 
use warnings; 

my $file_pattern = "whatever.you.look.for"; 
my $file_extension = "\.txt"; 

opendir(DIR, '/my/directory/') or die("Couldn't open dir"); 
while(my $name_in = readdir(DIR)) { 
    next unless($name_in =~ /$file_pattern/); 

    my ($name_base) = ($name_in =~ /(^.*?)$file_pattern/); 
    my $name_out1 = $name_base . "outfile1.txt"; 
    my $name_out2 = $name_base . "outfile2.txt"; 
    open(IN, "<", $name_in) or die("Couldn't open $name_in for reading"); 
    open(OUT1, ">", $name_out1) or die("Couldn't open $name_out1 for writing"); 
    open(OUT2, ">", $name_out2) or die("Couldn't open $name_out2 for writing"); 

    while(<IN>) { 
     # do whatever needs to be done 
    } 

    close(IN); 
    close(OUT2); 
    close(OUT1); 
} 
closedir(DIR); 

編輯:實施了擴展剝離,輸入文件句柄已關閉,現在已經過測試。

4
use File::Basename; 
$base = basename("infile.txt", ".txt"); 
print $base."_outfile1.txt";