Get the number of files that match a pattern in a directory and delete the oldest one

kshwildcards

I'd like to do the following:

  1. Get the number of files in a given directory that match a given pattern, for example:

    ExtractBackup_{date}.tar.gz

  2. If that number is 2 or higher, delete the oldest file which matches that pattern.

How do I go about doing this using a Korn Shell (.ksh) script?

Best Answer

There's no direct way to count files matching a pattern, but you can do it in two easy steps: generate the list of files, and take the length of the list. Assuming the date is in YYYYMMDD form (note that this clobbers the positional parameters):

set ExtractBackup_[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9].tar.gz
if [ -e "$1" ]; then count=$#; else count=0; fi

In ksh93, you can make the count easier by making the list be empty if no file matches. Portably, a pattern that doesn't match any file is replaced by a list containing one word which is the pattern itself; ksh93 has a construct to have the pattern expand to an empty list instead. Ksh has arrays, which means you don't need to clobber the positional parameters.

backups=(~(N:ExtractBackup_[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9].tar.gz))
count=${#backups[@]}

If the date is in YYYYMMDD form, then the oldest file is the first in the list.

set ExtractBackup_[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9].tar.gz
if [ $# -ge 2 ]; then rm "$1"; fi