So, we have a client’s backup program that saves a database to a file each night, but the file name just includes the date, not the days of the week. There are over a year of daily backups which are taking up a lot of space, and they only need to keep the weekly Friday night copy. Fortunately, with Linux the “date” command can help.

The following line will display the date with the day of the week based on the input 20170811:

$ date +%Y%m%d-%a -d 20170811
20170811-Fri

So, that’s a great start. We just need to input each file name, read the date in the name, then mv the old file name to a name with the new format including the day of the week. From there we can just move the files containing “Fri” to a separate folder and then delete the remaining ones. So, here is how I did that (minus the moving “Fri” files and deleting the rest).

#!/bin/bash
# Get the current folder so we can move back to it when the script wraps up
curfolder=`pwd`

# Save the folder where the backups are stored in a variable, this could be an input statement
folder="/backups/messedupnames/"

# Change to the folder in the $folder variable
cd $folder

# Create a variable for knowing which files to look for in the folder
filenamewild="mydata-backup-*"

for f in $filenamewild
do
# Strip off the extension, if your filenames have multiple "." you may need to change this
name=$(echo $f | cut -d\. -f-1)
# Get the date from the file name
filenamedate=$(echo $name | awk -F- '{ print $3 }' | awk -F. '{ print $1 }')
# Create the new date format including the day of the week
newfilenamedate=$(date +%Y%m%d-%a -d $filenamedate)
# Move the file (aka. rename the file)
mv $f mydata-backup-$newfilenamedate.sqlgz
done

# Move back to the original folder
cd $curfolder

And there you go. All the files now have the name format “mydata-backup-20170811-Fri.sqlgz”. No you are free to work on the files with the day of the week in the filename. For example, to delete all the Monday files:

$ rm -f /backups/messedupnames/*Mon*

If you have any suggestions or comments, please leave them below. Happy BASH’ing.