A bit of Perl

Needed to search a backup log for a line plus the two lines following it. I have used Perl in the past as it is loads quicker than shell scripting.

Using grep you can use -B num to set how many lines before the match and -A num for the number of lines after the match.

grep -B 3 -A 2  "RMAN ran okay..."   backup.log 

If you want the same number of lines before and after you can use -C num.

grep -C 3 "RMAN ran okay..." backup.log 

This will show 3 lines before and 3 lines after.
Although grep, egrep  achieved the objective, perl can give a more bespoke approach.


#!/usr/bin/perl
open(MYFILE, "./alert_database.log") || die "Can't open myfile: $!";
@stuff=<MYFILE>;
$last=$.;
print "Enter a search : \n";
my $pat=<STDIN>; chomp $pat;
for( $count=0; $count<$last; $count=$count+1) {
$a = $stuff[$count];
$nextline = grep { /$pat/ } $a;
if ($nextline == 1) {
print $stuff[$count];
print $stuff[$count+1];
print $stuff[$count+2];
print "\n\n\n";
};
}
close(MYFILE);


Variartion on this - search a file between two dates - no error checking :

#!/usr/bin/perl

## Usage :
## perl test.pl abc.txt "Wed Mar 27 13:12:58 UTC 2019" "Wed Mar 27 13:13:00 UTC 2019" > out.txt
## where abc.txt is file to search and strings to search between, output to out.txt


my $fname = $ARGV[0]; chomp $fname;
open(MYFILE, $fname) || die "Can't open myfile: $!";
@stuff=<MYFILE>;
$last=$.;
my $pat  = $ARGV[1] ; chomp $pat;
my $pat2 = $ARGV[2] ; chomp $pat2;

$pat3 = `grep -n "$pat" $fname | awk -F: '{print $1}'`;
$pat4 = `grep -n "$pat2" $fname | awk -F: '{print $1}'`;

$lines = $pat4 - $pat3;
for( $count=0; $count<$last; $count=$count+1) {
$a = $stuff[$count];
$nextline = grep { /$pat/ } $a;
if ($nextline == 1) {
for (my $i=0; $i <= $lines; $i++)
{ print $stuff[$count + $i]; }

};

}
close(MYFILE);


No comments:

Post a Comment