Sometimes I just want to change all of those ".MP3" extensions to ".mp3", or change an underscore that persists across several directories full of similarly named files, or just change the name of every file on my hard drive to something completely unrecognizable. You can always use
sed
and just pretend that everything looks right, but taking the extra step to make your sed
-soaked dreams a sharp and terrible reality requires just a bit more crazy. Luckily, I have that in spades.Enter the File Mangler! Yes, the actual filename 'rnmdir.sh' is much less impressive, but it really should be called 'mangles_all_your_freaking_files.sh'. The idea is simple: search for a bunch of files given a few criteria (or none whatsoever), and use regex to modify all the filenames using
sed
. Sounds simple enough, right?Perhaps I'm being paranoid, but I foresee the potential for a great deal of unintended destruction. That's why I made previewing the carnage the default behavior. You have to add a "-e" to the arguments and type "yes" in order to actually execute the mess. Don't say I didn't warn you...
Click to expand code
#!/bin/bash
if [ "$#" -lt "3" ]; then
echo "Usage: rnmdir.sh [-e] <some_dir> <search_regex> <sed_regex>"
echo " -e means execute. You probably don't want this."
exit
fi
execute=0
if [ "$1" == "-e" ]; then
execute=1
shift
fi
dir="$1"
filematch="$2"
transform="$3"
filelist=$(find -Es "$dir" -iregex "$filematch")
echo "Old:"
echo "$filelist"
echo
echo "New:"
echo "$filelist" | sed -E "$transform"
if [ "$execute" -eq "1" ]; then
echo "PREPARE TO MANGLE YOUR FILENAMES!"
echo "Are you REALLY sure you wish to continue? [yes/no]"
read response
if [ "$response" == "yes" ]; then
while read file; do
newfile=$(echo "$file" | sed -E "$transform")
echo "Renaming $file to $newfile"
mv "$file" "$newfile"
done < <(echo "$filelist")
else
echo "Operation cancelled"
fi
fi
if [ "$#" -lt "3" ]; then
echo "Usage: rnmdir.sh [-e] <some_dir> <search_regex> <sed_regex>"
echo " -e means execute. You probably don't want this."
exit
fi
execute=0
if [ "$1" == "-e" ]; then
execute=1
shift
fi
dir="$1"
filematch="$2"
transform="$3"
filelist=$(find -Es "$dir" -iregex "$filematch")
echo "Old:"
echo "$filelist"
echo
echo "New:"
echo "$filelist" | sed -E "$transform"
if [ "$execute" -eq "1" ]; then
echo "PREPARE TO MANGLE YOUR FILENAMES!"
echo "Are you REALLY sure you wish to continue? [yes/no]"
read response
if [ "$response" == "yes" ]; then
while read file; do
newfile=$(echo "$file" | sed -E "$transform")
echo "Renaming $file to $newfile"
mv "$file" "$newfile"
done < <(echo "$filelist")
else
echo "Operation cancelled"
fi
fi
No comments:
Post a Comment