Stateful tail (shows only newlines from the last execution)

I want to see how many lines have been added to the file since the last request without having to read the entire file again.

Sort of:

ptail my_file | fgrep "[ERROR]" | wc -l 

A solution in plain Perl would be preferable since I don't have easy access to the compiler.

+5
source share
4 answers

Although he used strings for other purposes, I wrote code that essentially is before.

, , ( ) inode ( stat) . , , inode ( stat). inode , ( , ..), ; .

+2

since , C.

+2

, Perl :

File::Tail::Multi

MultiTail, perl / .

File:: Tail:: Multi;

$tail1=File::Tail::Multi->new (  OutputPrefix => "f", 
                                 Debug => "$True", 
                                 Files => ["/var/adm/messages"]
                              );
while(1) {
    $tail1->read;
    #
    $tail1->print;
    sleep 10;
}
  • $tail1=File::Tail::Multi->new: ptail
  • Files = > /var/adm/messages
  • OutputPrefix = > , "LineArray"
  • $tail1->read:
  • $tail1->print: "LineArray";
+2

Perl:

#! /usr/bin/perl
# Perl clone of since(1)
# http://welz.org.za/projects/since
#

use strict;
use warnings;

use Fcntl qw/ SEEK_SET O_RDWR O_CREAT /;
use NDBM_File;

my $state_file = "$ENV{HOME}/.psince";

my %states;
tie(%states, 'NDBM_File', $state_file, O_CREAT | O_RDWR, 0660)
        or die("cannot tie state to $state_file : $!");

while (my $filename = shift) {
        if (! -r $filename) {
                # Ignore
                next;
        }
        my @file_stats = stat($filename);
        my $device = $file_stats[0];
        my $inode = $file_stats[1];
        my $size = $file_stats[7];
        my $state_key = $device . "/" .$inode;
        print STDERR "state_key=$state_key\n";

        if (! open(FILE, $filename) ) {
                print STDERR "cannot open $filename : $!";
                next;
        }

        # Reverting to the last cursor position
        my $offset = $states{$state_key} || 0;
        if ($offset <= $size) {
                sysseek(FILE, $offset, SEEK_SET);
        } else {
                # file was truncated, restarting from the beginning
                $offset = 0;
        }

        # Reading until the end
        my $buffer;
        while ((my $read_count = sysread(FILE, $buffer, 4096)) > 0) {
                $offset += $read_count;
                print $buffer;
        }
        # Nothing to read
        close(FILE);
        $states{$state_key} = $offset;
}

# Sync the states
untie(%states);

@Dave: , , tell, .

+2

All Articles