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

SOrt of a code sorting logic challenge:

Anyone have tips for ordering rotatelog2 lognames when loginterval changes? While archiving away older logs, my script must avoid archiving away the currently active log. I' have been using the max alpha file name to find the freshest (hence current & active) log to avoid

CustomLog "|/usr/sbin/rotatelogs2 /var/logs/access_log_%y_%m_%d_%H_%M_ +%S 10800 -300" accesslogformat
But due to naming magic of rotatelogs2, access_log_04_05_20_03_00_00 is fresher than access_log_04_05_20_03_30_00, even thoughit comes earlier in an alpha sort. While the log interval doesn't change often, it is changed occasionally, and hence this question

?

Replies are listed 'Best First'.
Re: ordring logrotate file names
by saskaqueer (Friar) on May 20, 2004 at 09:43 UTC

    I may have coded this wrong, but my sample data seems to work okay. This is probably highly inefficient, but it's fast enough for the job

    #!/usr/bin/perl -w $| = 1; use strict; my @sorted = map { $_->[0] } sort { ($a->[1] <=> $b->[1]) or ($a->[2] <=> $b->[2]) or ($a->[3] <=> $b->[3]) or ($a->[4] <=> $b->[4]) or ($a->[5] <=> $b->[5]) or ($a->[6] <=> $b->[6]) } map { m!^(access_log_(\d+)_(\d+)_(\d+)_(\d+)_(\d+)_(\d+))$! ? [$1, $2, $3, $4, $5, $6, $7] : () } <DATA>; print "Listed from oldest to newest:\n\n", join("\n", @sorted), "\n"; __DATA__ access_log_04_05_20_03_00_00 access_log_04_05_20_03_30_00 access_log_04_05_20_03_30_01 access_log_04_05_20_03_29_30 access_log_04_05_19_03_30_00 access_log_04_05_17_03_30_00 access_log_04_04_20_03_30_00 access_log_04_05_20_03_31_00

    Update: This one should be much much better. We can just strip everything but the digits and do a single comparision:

    use strict; my @sorted = map { $_->[0] } sort { $a->[1] <=> $b->[1] } map { chomp( my $x = $_ ); s!\D+!!g; [ $x, $_ ] } <DATA>; # for your case, we just pop() off the last element # (which would be the current log) and handle the rest! my $current = pop( @sorted ); warn( "$current is newest logfile, not touching it!\n" ); for my $log ( @sorted ) { # unlink( '/var/logs/' . $log; # or whatever } __DATA__ access_log_04_05_20_03_00_00 access_log_04_05_20_03_30_00 access_log_04_05_20_03_30_01 access_log_04_05_20_03_29_30 access_log_03_05_19_03_30_00 access_log_04_05_17_03_30_00 access_log_04_04_20_03_30_00 access_log_04_05_20_03_31_00