I'd like to do the following:
-
Get the number of files in a given directory that match a given pattern, for example:
ExtractBackup_{date}.tar.gz
-
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):
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.
If the date is in YYYYMMDD form, then the oldest file is the first in the list.