Apple - How to strip a filename of special characters?

If you have a specific set of characters that you want to keep, tr works very well.

For example

tr -cd 'A-Za-z0-9_-'

Will remove any characters not in the set of characters listed. (The -d means delete, and the -c means the complement of the characters listed: in other words, any character not listed gets deleted.)


This would only replace single quotes with underscores:

for f in *; do mv "$f" "${f//'/_}"; done

This would only keep alphanumeric ASCII characters, underscores, and periods:

for f in *; do mv "$f" "$(sed 's/[^0-9A-Za-z_.]/_/g' <<< "$f")"; done

Locales like en_US.UTF-8 use the ASCII collation order on OS X, but [[:alnum:]] and \w also match characters like ä in them. If LC_CTYPE is C, multi-byte characters are replaced with multiple underscores.


I recently had the same problem and had to strip the filenames of all files in a folder of special characters. I used this command, which is a combination of both answers posted here, but also keeps periods. Maybe it helps someone.

for file in *; do echo mv "$file" `echo $file | tr -cd 'A-Za-z0-9_.-'` ; done

removing the echo in front of mv "$file" executes the command.