2009-05-18 4 views
0

디렉토리의 각 파일을 읽고, 각 입력 파일의 결과를 두 개의 서로 다른 파일 (예 : 파일)로 출력하는 스크립트를 작성했습니다. "outfile1.txt"및 "outfile2.txt". 내가 원래 사람에게 내 결과 파일을 링크 할 수 있도록하려면, 그래서 어떻게 내가 이런 걸 얻을, 결과 파일 이름에 입력 파일 이름 (infile.txt)를 추가 할 수 있습니다Perl : 출력 파일 이름에 입력 파일 이름을 추가

infile1_outfile1.txt을

을 infile1_outfile2.txt

infile2_outfile1.txt, infile2_outfile1.txt

infile3_outfile1.txt, infile3_outfile2.txt ...?

도움 주셔서 감사합니다.

답변

6

에 대한 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

간단한 문자열 연결은 입력 파일 이름에서 "이 .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"; 
관련 문제