2009-05-18 17 views
0

ディレクトリ内の各ファイルを読み込み、何かを行い、各入力ファイルの結果を2つの異なるファイルに出力するスクリプトを作成しました。 "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」を削除するには、置換を使用して、適切なモジュールのためにここで働く、あるいはCPANになっているはずです。出力ファイル名を構築するための 使用し、文字列の連結:私が正しくあなたを理解していれば

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

、あなたはこのような何かを探していますか?

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"; 
関連する問題