• Jimmy Angelakos's picture

    tac is the opposite of cat

    Jimmy Angelakos / October 1, 2015
  • Sometimes it's better to read a file backwards, for instance when we're dealing with a huge logfile.

    Linux is covered in that respect, as it has the GNU tac utility which spits the file out backwards, line by line. However some *nix systems may not have tac but may indeed have Perl.

    So here is an implementation of tac in Perl, it may not be pretty or support all of the GNU utility's options, but it should work.

    #!/usr/bin/perl
    
    use Fcntl 'SEEK_CUR', 'SEEK_END';
    
    foreach my $file (@ARGV) {
        if ( -e $file ) {
            open FD, $file;
            seek FD, 0, SEEK_END;
            while () {
                seek FD, -2, SEEK_CUR;
                read FD, $charbuf, 1;
                if ($charbuf eq "\n") {
                    print $linebuf."\n";
                    $linebuf = "";
                    $charbuf = "";
                }
                $linebuf = $charbuf.$linebuf; 
                $charbuf = "";
                if (tell FD == 1) {last};
            }
            if ($linebuf ne "") {
                print $linebuf."\n";
            }
            close FD;
        }
    }

    nyan cat != tac nayn

    Attachments: