How can I print lines that match a pattern in Perl?

Posted by kivien on Stack Overflow See other posts from Stack Overflow or by kivien
Published on 2010-04-01T01:06:47Z Indexed on 2010/04/01 1:23 UTC
Read the original article Hit count: 489

Filed under:
|

Assuming the file.txt having just one sentence per line as follows:-

John Depp is a great guy.  
He is very inteligent.  
He can do anything.  
Come and meet John Depp.

The perl code is as follows:-

open ( FILE, "file.txt" ) || die "can't open file!";
@lines = <FILE>;
close (FILE);
$string = "John Depp";
foreach $line (@lines) {
    if ($line =~ $string) { print "$line"; }
}

The output is going to be first and fourth line.

I want to make it working for the file having random line breaks rather than one English sentence per line. I mean it should also work for the following:-

John Depp is a great guy. He is very inteligent. He can do anything. Come and meet John Depp.

The output should be first and fourth sentence.

Any ideas please?

© Stack Overflow or respective owner

Related posts about perl

Related posts about regex