Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Re: pattern matching only last line of a file and then copy 10 lines above till end

by saskaqueer (Friar)
on Oct 20, 2005 at 15:57 UTC ( [id://501712]=note: print w/replies, xml ) Need Help??


in reply to pattern matching only last line of a file and then copy 10 lines above till end

Here's one way. Note that my example clobbers any existing output file and replaces that data with the new 10 lines. If you need to append the data to existing content, make sure to change that part of the script.

One thing I noticed is how old fashioned I am when it comes to array indices; I prefer using $lines[($#lines - 10) .. $#lines] rather than $lines[-11 .. -1]. I guess I just don't like a negative index? I'm strange that way :)

#!/usr/bin/perl -w use strict; my $in_file = 'in.dat'; my $out_file = 'out.dat'; my $spec_text = qr/special text here/; while (1) { open(my $fh_in, '<', $in_file) or die("open failed: $!"); my @lines = <$fh_in>; close($fh_in); if ($lines[$#lines] =~ $spec_text) { open(my $fh_out, '>', $out_file) or die("open failed: $!"); print $fh_out @lines[($#lines - 10) .. $#lines]; close($fh_out); } sleep 60 * 30; # 30 minutes }

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://501712]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others chilling in the Monastery: (4)
As of 2024-04-25 07:00 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found