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.