将文件拆分为多个部分,然后在每个部分中搜索您的字符串:命名此脚本search.pl
#!/usr/bin/env perl
use strict;
use warnings;
my $text = <<EOTEXT;
---------------------
blah
moo
fubar
---------------------
funkytown
tic
tac
chili cheese hotdog
heartburn
---------------------
EOTEXT
my ($search) = $ARGV[0];
defined $search
or die "usage: $0 search_string\n";
# Split by dashes followed by whitespace (newlines)
my @sections = split /----*\s+/, $text;
my $found = 0;
for my $section (@sections) {
# use /s to search a multi-line section
if ($section =~ m/$search/s) {
print $section;
$found++;
}
}
print "Unable to find any matching sections for '$search'!\n"
unless $found;
exit !$found; # 0 = success
搜索tic
./search.pl tic
funkytown
tic
tac
chili cheese hotdog
heartburn
搜索foo
./search.pl foo
Unable to find any matching sections for 'foo'!