-1

I need to delete files of this type, except for the 2 newest files:

Ubuntu_Scripts_2018-08-22-20-00.zip 

which are located in

/media/andy/MAXTOR_SDB1/Ubuntu_Mate_18.04/Script_Backups/

This was provided by pa4080. I'd like to modify it for this purpose, if possible.

#!/bin/bash
TARGET_DIR='/media/andy/MAXTOR_SDB1/Ubuntu_Mate_18.04/'
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 {} +

I used #!/bin/bash -xv to study how it works.

Seth
  • 58,122
fixit7
  • 3,127

1 Answers1

0
# http://www.cs.columbia.edu/~tal/3261/fall07/handout/egrep_mini-tutorial.htm

#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'
#!/bin/bash
TARGET_DIR='/media/andy/MAXTOR_SDB1/Ubuntu_Mate_18.04/Script_Backups/'
REGEX='Ubuntu_Scripts_[0-9]{4}-[0-9]{2}-[0-9]{2}-[0-9]{2}-[0-9]{2}[.]zip' # Ubuntu_Scripts_2018-08-23-10-00.zip

LATEST_FILE="$(ls "$TARGET_DIR" | egrep "^${REGEX}$" | tail -1)"

find "$TARGET_DIR" ! -name "$LATEST_FILE" -type f -regextype egrep -regex ".*/${REGEX}$" -exec rm -f {} +
muru
  • 197,895
  • 55
  • 485
  • 740
fixit7
  • 3,127