Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Between Two Regex: Find the text between two lines that match regexes.
#!/usr/bin/env perl
use strict;
use warnings;
use Carp;
use v5.10;
use constant FALSE => 1==0;
use constant TRUE => not FALSE;
# Given two regex that match a start and end line, return blocks of
# text between lines like that.
#
# Invoke it like this:
#
# ./between_two_regex 'first line.' 'last line.' data_for_test.txt
$#ARGV == 2 or die "Error: You must pass two regex as arguments!";
my $start_line=shift;
my $end_line=shift;
my $start_line_seen=FALSE;
my $end_line_seen=FALSE;
while(<>){
m/$start_line/
and $start_line_seen=TRUE
and $end_line_seen=FALSE;
m/$end_line/
and $end_line_seen=TRUE
and $start_line_seen=FALSE;
$start_line_seen
and print qq{'$ARGV': $.: $_};
} continue {
# Reset $. at the end of each file
close ARGV if eof;
}
This is the first line.
a
b
c
This is the last line.
This text does not get captured.
This is the first line.
1
2
3
This is the last line.
This is some other text that doesn't match.
This is the first line.
A
B
C
This is the last line.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment