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
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
First I would suggest to use date and time format that will be parsed more easy. For example:
$ date '+%Y-%m-%d_%H:%M'
2018-08-21_21:41
Then you can use something as the follow, to keep only the newest file (reference):
#!/bin/bash
TARGET_DIR='./'
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):
#!/bin/bash
TARGET_DIR='./'
MAX_AGE='3 days ago'
AGE="$(date '+%Y%m%d%H%M' --date="$MAX_AGE")"
for file in "$TARGET_DIR"/*
do
CLR="$(echo $(basename "$file") | sed -e 's/-//g' -e 's/_//g' -e 's/://g')"
if [[ -f $file ]] && [[ $AGE -ge $CLR ]] 2>/dev/null
then
rm -f "$file"
fi
done
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:
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
Aug 20 '18 at 21:36
%Y%m%d_%H%M
– steeldriver Aug 20 '18 at 19:53