Once I find a string in a file, how can I read all of the lines between two lines in that file

68 Views Asked by At

I have a file like this - just much bigger:

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

How can I search for 'tic' and output everything between the 2nd and 3rd set of dashed lines?

block_with_string.pl tic 

should output

funkytown
tic
tac
chili cheese hotdog
heartburn

I appreciated this answer for printing all lines between 2 lines - just need an extra step.

To be honest, what I have is a continuous logfile of XML/SAP IDOCs. I've just not had any luck locating any helpful IDOC-centric perl info.

1

There are 1 best solutions below

0
On

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'!