I use this to make it easier to see when a backup script ran.

touch /media/andy/MAXTOR_SDB1/Ubuntu_Mate_18.04/$( date '+%m-%d-%Y_%I:%M-%p' )

I would like a script that would delete all but the newest file ONLY of this type 08-20-2018_01:24-PM

  • What tool are you using for the backup Commented Aug 20, 2018 at 18:27
  • 2
    It will be much simpler if you choose a date format that sorts lexically in your locale - for example, %Y%m%d_%H%M Commented Aug 20, 2018 at 19:53
  • @George Udosen I use a backup script I made.
    – fixit7
    Commented Aug 20, 2018 at 21:22

1 Answer 1


First I would suggest to use date and time format that will be parsed more easy. For example:

$ date '+%Y-%m-%d_%H:%M'

Then you can use something as the follow, to keep only the newest file (reference):

REGEX='[0-9]{4}-[0-9]{2}-[0-9]{2}_[0-9]{2}:[0-9]{2}'   # regular expression that match to: date '+%Y-%m-%d_%H:%M'
LATEST_FILE="$(ls "$TARGET_DIR" | egrep "^${REGEX}$" | tail -1)"
find "$TARGET_DIR" ! -name "$LATEST_FILE" -type f -regextype egrep -regex ".*/${REGEX}$" -exec rm -f {} +

If you want to delete a number of files that are older than a period of time you could use something as this (source of the idea):

MAX_AGE='3 days ago'
AGE="$(date '+%Y%m%d%H%M' --date="$MAX_AGE")"

for file in "$TARGET_DIR"/*
    CLR="$(echo $(basename "$file") | sed -e 's/-//g' -e 's/_//g' -e 's/://g')"

    if [[ -f $file ]] && [[ $AGE -ge $CLR ]] 2>/dev/null
        rm -f "$file"

Another option is to use find and delete the files older than a period of time, based on their date of creation. For example the next command will delete all files older than 2 days:

find /path/ -mtime +2 -type f -delete

Ideas for complete backup scrips could be found at:

  • To perform my tests, I've used this command to generate a couple of empty files: for i in {0..10}; do touch $(LC_TIME=C date '+%Y-%m-%d_%H:%M' --date="$i days ago") -d "$i days ago"; done
    – pa4080
    Commented Aug 20, 2018 at 21:36
  • I prefer month day year format. (I'm American)
    – fixit7
    Commented Aug 21, 2018 at 1:06

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .