Executing grep via Perl

2.1k views Asked by At

I am new to Perl. I am trying to execute grep command with perl.

I have to read input from a file and based on the input, the grep has to be executed.

My code is as follows:

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

#Reading input files line by line
open FILE, "input.txt" or die $!;
my $lineno = 1;
while (<FILE>) {

        print " $_";
        #This is what expected.
        #our $result=`grep -r Unable Satheesh  > out.txt`;
        our $result=`grep -r $_ Satheesh  > out.txt`;
        print $result

}
print "************************************************************\n";

But, if I run the script, it looks like a infinite loop and script is keep on waiting and nothing is printed in the out.txt file.

1

There are 1 answers

0
Barmar On BEST ANSWER

The reason it's hanging is because you forgot to use chomp after reading from FILE. So there's a newline at the end of $_, and it's executing two shell commands:

grep -r $_
Satheesh > out.txt

Since there's no filename argument to grep, it's reading from standard input, i.e. the terminal. If you type Ctl-d when it hangs, you'll then get an error message telling you that there's no Satheesh command.

Also, since you're redirecting the output of grep to out.txt, nothing gets put in $result. If you want to capture the output in a variable and also put it into the file, you can use the tee command.

Here's the fix:

while (<FILE>) {

        print " $_";
        chomp;
        #This is what expected.
        #our $result=`grep -r Unable Satheesh  > out.txt`;
        our $result=`grep -r $_ Satheesh | tee out.txt`;
        print $result

}