假设file.txt每行只有一个句子,如下所示:
约翰德普是个好人。 他很聪明。 他可以做任何事情。 来见见约翰德普。
Perl 代码如下:-
open ( FILE, "file.txt" ) || die "can't open file!";
@lines = <FILE>;
close (FILE);
$string = "John Depp";
foreach $line (@lines) {
if ($line =~ $string) { print "$line"; }
}
Run Code Online (Sandbox Code Playgroud)
输出将是第一行和第四行。
我想让它适用于具有随机换行符的文件,而不是每行一个英文句子。我的意思是它也应该适用于以下内容:-
约翰德普是个好人。他非常聪明。他可以做任何事情。来见见约翰德普。
输出应该是第一句和第四句。
请问有什么想法吗?
单程
while(<>){
if (/John Depp/i){
@s = split /\s*\.\s*/;
foreach my $line (@s){
@f=split /\s*\.\s*/ , $line;
foreach my $found (@f){
if ($found =~/John Depp/i) {
print $found."\n";
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
输出
$ cat file
John Depp is a great guy.
He is very inteligent.
He can do anything.
Come and meet John Depp.
John Depp is a great guy. He is very inteligent. He can do anything. Come and meet John Depp.
$ perl perl.pl file
John Depp is a great guy
Come and meet John Depp
John Depp is a great guy
Come and meet John Depp
Run Code Online (Sandbox Code Playgroud)