Created
October 1, 2012 05:03
-
-
Save davesque/3809548 to your computer and use it in GitHub Desktop.
Rename files in year directories
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
# Custom move command that will create the destination directory if it does not | |
# exist. | |
function my_mv() { | |
# If two arguments were passed and the first argument was a file that exists | |
if [[ $# == 2 && -e $1 ]] | |
then | |
# Get the directory name of the second argument ("testing/test.txt" -> | |
# "testing") | |
local dir=$(dirname $2) | |
# If the directory does not exist... | |
if [[ ! -d $dir ]] | |
then | |
# ...make it... | |
mkdir -p $dir | |
fi | |
# ...then move the file into it. | |
mv $1 $2 | |
fi | |
} | |
# Get the current directories in root (the subject directories). These will be | |
# deleted after the script runs. | |
subjects=$(ls -1 -d */) | |
# Loop through all files and move them | |
for file_a in $(find .) | |
do | |
# Match files which have a './subject/year/month/filename' pattern | |
if [[ $file_a =~ ^\./([^\.].*)/([0-9]{4})/[0-9]{1,2}/([^/]+)$ ]] | |
then | |
# Get the subject, year, and name from the regular expression match | |
subject=${BASH_REMATCH[1]} | |
year=${BASH_REMATCH[2]} | |
name=${BASH_REMATCH[3]} | |
# Create the new file name | |
file_b="./$year/$subject/$name" | |
# Do the renaming | |
echo "Renaming $file_a to $file_b ..." | |
my_mv $file_a $file_b | |
fi | |
done | |
# Remove subject directories in root. Unless you're totally sure what you're | |
# doing, leave this commented out and delete those subject folders manually. | |
# You'll be very unhappy if you run this script in the wrong folder. | |
# rm -rf $subjects |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment