JArner has asked for the wisdom of the Perl Monks concerning the following question:

Hello Monks, I found a bit of code searching for a way to clean up an 80G log file that is eating up space on a server. I don't want to just erase everything, I would like to keep 6 months of history at least. Would you be able to help me understand this bit of code? And make it useful for this purpose?

perl -i.~ -MTime::Local -ane'BEGIN { @months{ qw( Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec ) } = 1 .. 12; ( $day, $month, $year ) = (localtime)[ 3 .. 5 ]; $my_dt = timelocal( 0, 0, 0, $day, $month, $year ) - 2 * 60 * 60 * 2 +4; } @dt = split /-/, $F[0]; print if timelocal( 0, 0, 0, $dt[0], $months{ $dt[1] } - 1, $dt[2] ) >= $my_dt ' logfile

The logfile has entries as follows...

Jan 26 03:41:14 tul-access-5-8 mgd[61746]: UI_CHILD_STATUS: Cleanup child '/usr/sbin/smid', PID 61756, status 0

Any help in this matter would be greatly appreciated. -Jim

Replies are listed 'Best First'.
Re: Script to clean up a log file based on timestamps
by NetWallah (Canon) on Oct 29, 2014 at 00:42 UTC
    That script uses the following perl flags:

    -a autosplit mode with -n or -p (splits $_ into @F)
    -n assume "while (<>) { ... }" loop around program
    -i[extension] edit <> files in place (makes backup if extension supplied)

    in addition to the standard "-e" for execute, and -M to include the module.

    The executable code starts with a BEGIN{} block that sets up the current date/time into $my_dt.

    The first statement uses the auto-split input line, and extracts the date pieces into @dt.

    After that, it is a matter of comparing the dates, and deciding whether to print to stdout.

    Your key to using it is to figure out how to correctly populate @dt, based on the contents of @F[0..2].

            "You're only given one little spark of madness. You mustn't lose it."         - Robin Williams

      Your key to using it is to figure out how to correctly populate @dt, based on the contents of @F[0..2].

      :) Time::Piece is much more convenient

Re: Script to clean up a log file based on timestamps
by Anonymous Monk on Oct 29, 2014 at 00:00 UTC

    Would you be able to help me understand this bit of code? And make it useful for this purpose?

    No thanks. Skip that piece of code and read perlintro (and read it well, from the beginning), read when it talks about creating and initializing variables with my, opening files with open/binmode, reading the files in a while loop with readline, print strings to new file handle, and testing strings with m//atch operator in Simple matching/perlrequick

    Editing a file is fours steps

    • read original-file
    • modify data
    • write new-file
    • rename new-file to original-file

    And maybe read Path::Tiny if you like convenience methods

    Your timestamps do not contain a year ... how will you know what year to start with?

    :)