Fun Scripting Problem

Robert Bonomi bonomi at
Wed Feb 13 21:08:44 UTC 2013

> Date: Wed, 13 Feb 2013 12:27:31 -0600
> From: Tim Daneliuk <tundra at>
> Subject: Fun Scripting Problem
> I know how to do this in Python, but I really want to do it in
> straight Bourne shell.  I have some ideas, but I thought I'd
> give you folks a crack at this Big Fun:
> a)  You have a directory of files - say they're logs - generated
>      at nondeterministic intervals.  You may get more than one a day,
>      more than one a month, none, or hundreds.
> b) To conserve space, you want to keep the last file generated
>     in any given month (the archive goes back for an unspecified
>     number of years), and delete all the files generated prior to
>     that last file in that same month.
> c) Bonus points if the problem is solved generally for either files
>     or directories generated as described above.
> These are not actually logs, and no, I don't think logrotate can
> do this ... or can it?

here's a one-liner:
 rm ` \
 stat -f "%SB %B %N" *  \
 | sort -k5nr \
 | cut -c1-7,17-20,32- \
 | awk 'BEGIN {a="";b=0;c=0} $1==a && $2==b && $3=c {print $4;}{a=$1;b=$2;c=$3}' \

This selects on creation date. change the B (both of them) in the stat
call to use a different timestamp

More information about the freebsd-questions mailing list