-2

我有一个像这样的文件 - 更大:

---------------------
blah
moo 
fubar
---------------------
funkytown
tic
tac
chili cheese hotdog
heartburn
---------------------

如何搜索“tic”并输出第二组和第三组虚线之间的所有内容?

block_with_string.pl tic 

应该输出

funkytown
tic
tac
chili cheese hotdog
heartburn

我很欣赏这个打印两行之间所有行的答案- 只需要一个额外的步骤。

老实说,我拥有的是 XML/SAP IDOC 的连续日志文件。我只是没有找到任何有用的以 IDOC 为中心的 perl 信息。

4

1 回答 1

2

将文件拆分为多个部分,然后在每个部分中搜索您的字符串:命名此脚本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'!
于 2015-08-07T02:22:35.227 回答