my file is like
line 1
line 2
line 3
target
line 5
line 6
line 7
I can write a regex that matches the target. What all I need is I need to grab lines 2,3,5,6. Is there any way to do it?
m operator in Perl is used to match a pattern within the given text. The string passed to m operator can be enclosed within any character which will be used as a delimiter to regular expressions.
If you really want to get compact, you could do my $next = <$fh>; while(my $line = $next) { $next = <$fh>; ... }
Digit \d[0-9]: The \d is used to match any digit character and its equivalent to [0-9]. In the regex /\d/ will match a single digit.
Perl Pattern Matching. Patterns are subject to an additional level of interpretation as a regular expression. This is done as a second pass, after variables are interpolated, so that regular expressions may be incorporated into the pattern from the variables.
If you're not determined to use perl
you can easily extract the context you want with grep
and Context Line Control options
grep -A 2 -B 2 target filename | grep -v target
Of course target
will need to be replaced by a suitable regex.
Robert is on the right path. You have to multiline your regex and match the 2 previous and next lines:
#!/usr/bin/perl -w
my $lines = <<EOF
line 1
line 2
line 3
target
line 5
line 6
line 7
EOF
;
# Match a new line, then 2 lines, then target, then 2 lines.
# { $1 } { $3 }
my $re = qr/^.*\n((.*?\n){2})target\n((.*?\n){2}).*$/m;
(my $res = $lines) =~ s/$re/$1$3/;
print $res;
@lines = ('line 1', 'line 2', 'line 3', 'target', 'line 5', 'line 6', 'line 7');
my %answer;
$regex = 'target';
for my $idx (0..$#lines) {
if ($lines[$idx] =~ /$regex/) {
for $ii (($idx - 2)..($idx + 2)){
unless ($lines[$ii] =~ /^$regex$/) {$answer{$ii} = $lines[$ii];}
}
}
}
foreach $key (sort keys %answer) { print "$answer{$key}\n" }
Which yields...
[mpenning@Bucksnort ~]$ perl search.pl
line 2
line 3
line 5
line 6
[mpenning@Bucksnort ~]$
Fixed for @leonbloy's comment about multiple target strings in the file
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With