Fun Scripting Problem

Karl Vogel vogelke+unix at pobox.com
Thu Feb 14 00:01:32 UTC 2013


>> On Wed, 13 Feb 2013 12:53:32 -0600, 
>> Tim Daneliuk <tundra at tundraware.com> said:

T> The only way to determine the date of the file is by looking at its stat
T> info.  There is nothing the file name or content that could be used to
T> infer this.

   Being a pedantic twit, I interpreted "stat info" to mean "info you can
   get from something that calls stat()".  The script below runs on BSD,
   Linux, or Solaris if you have GNU find installed.  Season to taste.

-- 
Karl Vogel                      I don't speak for the USAF or my company
Mom was so overprotective, she only let us play "Rock, Paper".

---------------------------------------------------------------------------
#!/bin/ksh
# usage: keepfiles DIR

export PATH=/usr/local/bin:/bin:/usr/bin
tag=${0##*/}
here=$(pwd)
tmp="$here/keep$$"

# Sanity check.
die () { echo "$tag: FATAL: $@" >&2; exit 1; }

# Don't repeat yourself.  Use undocumented option %Ts to
# avoid dealing with fractional seconds.
listdir () { find . -type f -printf "%TY%Tm%Td %Ts|%p\n"; }

case "$#" in
    0) die "need a directory" ;;
    *) work="$1" ;;
esac

# List files by date generated.
mkdir $tmp    || die "$tmp: mkdir failed"
test -d $work || die "$work: not a directory"
cd $work      || die "cd $work failed"

months=$(listdir | cut -c1-6 | sort -u)
for mon in $months
do
    listdir |                             # Get the files to check,
      grep "^$mon" |                      # ... look for each month,
      sort -n |                           # ... sort by modtime,
      cut -d'|' -f2 |                     # ... get the path,
      tail -1 |                           # ... last one's oldest,
      sed -e 's!^\(.*\)!mv \1 '$tmp'!' |  # ... write a mv command,
      sh                                  # ... and run it.
done

# Clean up.
cd $here
echo "Keep the stuff in $tmp"
exit 0


More information about the freebsd-questions mailing list