Created
March 29, 2015 20:02
-
-
Save raym/cdadeecf6a0245cd23da to your computer and use it in GitHub Desktop.
mv all files in a directory with a particular extension -- remove dashes, underscores, spaces, dots (add more if you like) and lowercase the filename
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
#!/bin/bash | |
ext=.png | |
for file in *$ext; do | |
baseName=${file%$ext} | |
baseNoDashes=$(echo $baseName | tr -d '_- .') | |
baseLower=$(echo $baseNoDashes | tr '[:upper:]' '[:lower:]') | |
fileNew=$baseLower$ext | |
echo Renaming $file to $fileNew | |
#mv $file $fileNew #uncomment to actually do it | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Very cool! Some notes:
The beginning of the for loop is safer as:
In bash, whenever you are doing substitution or interpolation, it should be done inside of double-quotes. There are some weird rules around expansion and parsing that can catch you off-guard. It is not always a sane system.
So the same would be true everywhere you're using the
$()
construct to run a command and get its output back. Also for thefileNew
declaration.Another note in case you're not aware - variables in bash are global by default. If you want lexical scoping in the for loop you have to use the
local
directive when declaring variables.Other than that it looks good!
PS. One trick I like to avoid having a line in the script that you comment or uncomment is to add a
--really-do-it
flag to the script. I.e. when you run the script, you'll get to themv
statement where you have an if statement that checks if the--really-do-it
flag was set. If it was set, actually do themv
, otherwise sayecho "Not actually moving since you didn't specify --really-do-it"
.