in reply to Regex question
TIMTOWTDI (and inelegant and verbose, but I think, 'linear and explicit'). Think in terms of removing 6 lines, rather than 5 and 1.
#!C:/perl/bin use strict; use warnings; # /me is too bleary at this hour to eliminate the "Usel +ess use of private variable in void context at ..." (lines 56 & 61) if (!$ARGV[0]) { print "Useage: perl 738855.pl String_to_search_for\n"; exit; } my $regex_string = $ARGV[0]; my $re = qr/$regex_string/; my @data_array; while (my $line = <DATA>) { chomp($line); push @data_array, $line; } my $flag = ''; my $test_line; my @cache; for $test_line(@data_array) { $test_line =~ /($re)/; if ($1) { $flag = "Found"; push @cache, "$flag"; next; } else { push @cache, $test_line } } # print Dumper @cache; my $i = 0; my $cache; for $cache(@cache) { if ( $cache =~ /Found/ ) { last; } else { $i++; } } # print "\$i: $i\n"; # $i = 6 when using the __DATA__ below my $j = ( $i - 5 ); # "-5": 5 preceding lines (and current + line) to delete for ($j; $j <= $i; ++$j ) { $cache[$j] = ''; } $j = $i; for ( $j; $j <= ($i+3); ++$j ) { # "$i+3" 3 following lines to disc +ard $cache[$j] = ''; } for $cache(@cache) { if ($cache) { print "$cache \n"; } else { next; } } __DATA__ Line 1 Line 2 should be removed line 3 should be removed line 4 should be removed line 5 should be removed line 6 should be removed line 7 should be removed this has more than 5 preceding lines and more + than 3 following lines. FOO line 8 should be removed line 9 should be removed line 10 should be removed line 11
Except for the warnings noted above, output is as desired:
hthLine 1 line 11
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Regex question
by jamsda (Novice) on Jan 26, 2009 at 05:07 UTC | |
by ikegami (Patriarch) on Jan 26, 2009 at 05:16 UTC |