0

Dear all
I would like to read every file in a directory, if each file contains a line 'KAC 50' I will write to an output file. My code below write all the out output into only 1 file. How can I have many output files corresponding to the input files?

#!/usr/bin/perl
use strict;
use warnings;

my $outfile = "KAC.pdb";
open(my $fh, '>>', $outfile);

opendir (DIR, "/data/tmp") or die "$!";
my @files = readdir (DIR);
closedir DIR;

foreach my $file(@files){
open (FH, "/data/tmp/$file") or die "$!";
while (<FH>){
my($line) = $_;
chomp($line);
if ($line =~m/KAC 50/){
print $fh $_;
}
}
}
close FH;

Best regards
becon

2
Contributors
2
Replies
4
Views
6 Years
Discussion Span
Last Post by becon
0

I haven't tested this but something like the following should work. It opens a new file for output using a prefix plus the input file name for the name of each output file.

#!/usr/bin/perl
use strict;
use warnings;

#If you want to open a new output file for every input file
#Do it in your loop, not here.
#my $outfile = "KAC.pdb";
#open( my $fh, '>>', $outfile );

opendir( DIR, "/data/tmp" ) or die "$!";
my @files = readdir(DIR);
closedir DIR;

foreach my $file (@files) {
    open( FH, "/data/tmp/$file" ) or die "$!";
    my $outfile = "output_$file"; #Add a prefix (anything, doesn't have to say 'output')
    open(my $fh, '>', $outfile);
    while (<FH>) {
        my ($line) = $_;
        chomp($line);
        if ( $line =~ m/KAC 50/ ) {
            print $fh $_;
        }
    }
    close($fh);
}
0

Dear David Ellis
I got the solution. Thank you very much.
becon

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.