henry_kmc
henry_kmc

Reputation: 13

Using Perl to find a keyword from a file and output to a text file

I have a text file containing a list of path.
e.g path.txt

/project/results/ver1/  
/project/results/ver2/  
/project/results/ver1000/  

And in every path it contains a file called report.txt. I am writing a perl program to go read the path.txt file line by line and descend into the path and grep the file report.txt.
I need to catch a keyword in the file by using a grep function.
Then I will extract my results to another text file.

I tried writing the perl program and it seems does not work. Pardon me as I am still new to programming.

my $output = ("output.txt");
my $path = ("path.txt"); 
open (OUT,'>',$output) or die;  
open (PATH, '<',$path) or die;  
foreach (<PATH>){  
chomp;  
$path1 = $_;  
chdir ("$path1");  
my $ans = grep 'Total Output Is' , report.txt;  
print OUT "$ans\n";  
chdir($pwd);  
}  

Upvotes: 1

Views: 303

Answers (2)

janos
janos

Reputation: 124724

Why not use a simple and straightforward plain old bash:

while read path; do
    grep 'Total Output Is' "$path"/report.txt
done < path.txt > output.txt

Upvotes: 0

mpapec
mpapec

Reputation: 50657

my $output = "output.txt";
my $path = "path.txt"; 
open (OUT,  '>', $output) or die $!;  
open (PATH, '<', $path) or die $!;

while (my $path1 = <PATH>) {
  chomp $path1;

  open my $fh, "<", "$path1/report.txt" or die $!;  
  /Total Output Is/ and print OUT $_ while <$fh>;
  close($fh);
}

close(OUT);
close(PATH);

Upvotes: 1

Related Questions