tags:

views:

432

answers:

4

I wrote a script that reads each file in a directory, does something and outputs results from each input file to two different files, e.g. "outfile1.txt" and "outfile2.txt". I want to be able to link my resulting files to original ones, so how can I add input filename (infile.txt) to the resulting filenames, to get something like this:

infile1_outfile1.txt, infile1_outfile2.txt

infile2_outfile1.txt, infile2_outfile2.txt

infile3_outfile1.txt, infile3_outfile2.txt ...?

Thanks for any help!

A: 

simple string concatenation should work here, or look on cpan for an appropriate module

ennuikiller
+4  A: 

Use a substitution to remove the ".txt" from the input filename. Use string concatenation to build your output file names:

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";
philippe
A: 

If I understand you correctly, are you looking for something like this?

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 );

Edit: Extension stripping implemented, input file handle closed, and tested now.

Olfan
+4  A: 
use File::Basename;
$base = basename("infile.txt", ".txt");
print $base."_outfile1.txt";
Matt G