How can I print lines that match a pattern in Perl?
- by kivien
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?