1820266 Members
2921 Online
109622 Solutions
New Discussion юеВ

PERL pattern matching

 
Anand_30
Regular Advisor

PERL pattern matching

I am writing a PERL script which is required to search a pattern and display 2 lines before the first occurance of the pattern.

Somehow I am not able to get the information using my script.

Can anyone please let me know how to do it.

Thanks,
Anand

2 REPLIES 2
Hein van den Heuvel
Honored Contributor

Re: PERL pattern matching

Please try to GOOGLE your questions before posting.

This has been asked and answered many many times before. For example in this forum:

Google: +perl +lines +before +site:itrc.hp.com


http://forums1.itrc.hp.com/service/forums/questionanswer.do?threadId=630972


Hein.
James R. Ferguson
Acclaimed Contributor

Re: PERL pattern matching

Hi:

Here's a simple solution:

# cat .findpat
#!/usr/bin/perl
use strict;
use warnings;
my $pat = shift;
my @lines;
while (<>) {
shift @lines if $#lines >= 2;
if (/$pat/) {
print for @lines;
print;
}
push( @lines, $_ );
}
1;

...Run as:

# ./findpat pattern file

Regards!

...JRF...