Freeman
Freeman

Reputation: 7

return lines with matching pattern from a file in perl

I need to write a perl script to extract the lines matching different patterns and then operate onto it. I've done following to match and extracts all the lines which contain the matching pattern:

my $filetoread = <$curr_dir/p*.out>;
my $filetoreadStrings=`strings $filetoread | egrep \"(Preparing extraction | 100.00%)\"`;
my @ftr = split('\n', $filetoreadStrings);
chomp (@ftr);

my $FirstPattern = (grep /Preparing extraction/, @ftr)[0];
my $SecondPattern = (grep /100.00% done/, @ftr)[0];
print "$FirstPattern \n";
print "$SecondPattern \n";

I'm getting lines with the second pattern only, even though the first pattern (Preparing extraction) is present in the log. I think the problem is with or '|'. I need to know how to get all the lines matching the patterns. [$curr_dir is the directory I'm running the script from and P*.out is the log file]

Upvotes: 0

Views: 963

Answers (1)

ikegami
ikegami

Reputation: 385506

`... egrep \"(Preparing extraction | 100.00%)\" ...`

should be

`... egrep \"(Preparing extraction| 100.00%)\" ...`

or just

`... egrep "(Preparing extraction| 100.00%)" ...`

my $filetoread = <$curr_dir/p*.out>;

should be

my ($filetoread) = <$curr_dir/p*.out>;

Don't call <glob_pattern> in scalar context unless you call it until it returns undef.


my @ftr = split '\n', `...`;
chomp(@ftr);

should be

my @ftr = split /\n/, `...`;

or

chomp( my @ftr = `...` );

Upvotes: 2

Related Questions