Perl: adding input file name to output file name

I wrote a script that reads every file in a directory, does something, and outputs the results from each input file to two different files, eg. outfile1.txt and outfile2.txt. I want to be able to link my resulting files to the original ones, since I can add the 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!

0


a source to share


4 answers


Use substitution to remove ".txt" from the input filename. Use string concatenation to create the names of your output files:



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

      

+6


a source


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

      



+4


a source


simple string concatenation should work here or look at cpan for the corresponding module

0


a source


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: extended descriptor, input file descriptor closed and tested.

0


a source







All Articles