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 }
In reply to Re: pattern matching only last line of a file and then copy 10 lines above till end
by saskaqueer
in thread pattern matching only last line of a file and then copy 10 lines above till end
by ultibuzz
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |