Sunday, March 17, 2002, 9:44:49 PM, swansong wrote:

> I'm fairly certain I'm attacking this incorrectly, so any advice is
> greatly appreciated...

> Task:

> I want to sort through my Solaris syslog (/var/adm/messages) looking for
> any system
> reboots which always start with the string SunOS and, if found, return
> that line and
> the next 20 lines, at least for starters.

> I was going to try and catch the line # of the line that has the SunOS
> in it and then
> increment that by 1, print that line from the array and then increment
> by 1 for 20
> iterations.

> I scratching out something such as.....(I'm a complete newbie and I'm
> banging my head
> against the wall because either I'm completely attacking this with the
> wrong logic and/or
> I'm misinterpreting the usage of $.     ......me thinks...help
> please...)


> #!/usr/local/bin/perl -w

> $file="/var/adm/messages";

> printf "test of the emergency broadcast system\n";

> open (FILE, "< $file") or die "can't open $file: $!";
> @lines = <FILE>;

>     foreach (@lines) {
>         if ($_ =~ /SunOS/)
>         printf "$_\n";      {
>         for ($i = $.; $i ($. + 20);$.++)
>         printf $lines[$i];
>    }
> }


It looks like your basic idea is sound, but there's a couple
of little problems. Where you've got printf you should have
print - they're different. see perldoc -f printf for the
difference. Also in your for loop there's something dodgy
with "$i ($. + 20)".

Also you want to be careful with "@lines = <FILE>" because
the whole file will be read into memory; if the file is huge
then it might cause problems.

Try this:

   #!/usr/bin/perl -w

   use strict;

   my $file = "/var/adm/messages";

   open (FILE, $file) or die $!;
   while (<FILE>) {
     if (/^SunOS/) {
       print;
       my $stop = $.+20;
       while (<FILE>) {
         last if $.>$stop;
         print;
       }
     }
   }

$. is automagically incremented for each line read from a
file, so we say, "read lines from a file, until we find one
starting 'SunOS', then carry on reading lines. Stop after 20
of them"

There is a case where there could be less than 20 lines
before the end of the file, which this solution handles.
However it doesn't handle the case where the string SunOS
appears within the 20 rows we output.



-- 
Best Regards,
Daniel                   [EMAIL PROTECTED]


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to