Remove All Illegal Characters from All Filenames in a Given Folder

Solution 1:

The only characters that are not allowed in filenames in OS X are NUL and either ASCII forward slash or ASCII colon depending on the context. Characters that appear as forward slashes in Finder appear as colons in shells and vice versa.

You might use shell commands like this though:

for f in *;do mv "$f" "${f//[^0-9A-Za-z.]}";done
find . -type f|while read f;do b=${f##*/};mv "$f" "${f%/*}/${b//[^[:alnum:].]}";done
brew install rename;find . -type f -exec rename 's/[^0-9A-Za-z.\/]/-/g;s/-+/-/g' {} \;
rename -z *

Or just use an application like Name Mangler:

Solution 2:

I wrapped this into an application, so you can easily redistribute it. It'll ask for a folder, and then sanitize the file names.

https://github.com/slhck/sanitize-filenames

You can also manually create the following application in Automator:

All you have to do is:

  • Ask for Finder items (you should allow only folders)

  • Set this result as a variable

  • Run a shell script (you need to pass input as arguments instead of to stdin)

      for f in "$1"/*; do
        dir="$(dirname "$f")"
        file="$(basename "$f")"
        mv -- "$f" "${dir}/${file//[^0-9A-Za-z.]}"
      done