我有一个这样的文件 - 只是更大:
---------------------
blah
moo
fubar
---------------------
funkytown
tic
tac
chili cheese hotdog
heartburn
---------------------
我如何搜索' tic'并在第2和第3组虚线之间输出所有内容?
block_with_string.pl tic
应输出
funkytown
tic
tac
chili cheese hotdog
heartburn
我赞赏this answer打印两行之间的所有行 - 只需要一个额外的步骤。
老实说,我所拥有的是XML / SAP IDOC的连续日志文件。我没有任何运气找到任何有用的以IDOC为中心的perl信息。
答案 0 :(得分:1)
Split your file into sections, and then search each section for your string:
Name this script 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
Search for tic
./search.pl tic
funkytown
tic
tac
chili cheese hotdog
heartburn
Search for foo
./search.pl foo
Unable to find any matching sections for 'foo'!