Skip to content

Instantly share code, notes, and snippets.

@raym
Created March 29, 2015 20:02
Show Gist options
  • Save raym/cdadeecf6a0245cd23da to your computer and use it in GitHub Desktop.
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
#!/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
@bitops
Copy link

bitops commented Mar 31, 2015

Very cool! Some notes:

The beginning of the for loop is safer as:

for file in "*$ext"

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 the fileNew 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 the mv statement where you have an if statement that checks if the --really-do-it flag was set. If it was set, actually do the mv, otherwise say echo "Not actually moving since you didn't specify --really-do-it".

@raym
Copy link
Author

raym commented Apr 4, 2015

thanks!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment