Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

regex

perl

Assuming file.txt has 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 intelligent. He can do anything. Come and meet John Depp.

The output should be first and fourth sentences.

Any ideas please?

like image 870
kivien Avatar asked Apr 01 '10 01:04

kivien


1 Answers

More simple: if you assume "sentences" are separated by dots, then you can use that as field separator:

 $/ = '.';
 while(<>) {
        print if (/John Depp/i);
 }
like image 185
leonbloy Avatar answered Sep 28 '22 00:09

leonbloy