Andy Andy - 17 days ago 5
Linux Question

How to remove special characters in file names?

When creating playlists I often came across files that would break the playing process. Such would be files with spaces or apostrophes. I would fix it with the following command

for file in *.; do mv "$file" `echo $file | tr " " '_'` ; done **(for spaces)**


Now I more often come across files with commas, apostrophes, brackets and other characters. How would I modify the command to remove such characters?

Also tried
rename 's/[^a-zA-Z0-9_-]//' *.mp4
but it doesnt seem to remove spaces or commas

Answer

Your rename would work if you add the g modifier to it, this performs all substitutions instead of only the first one:

$ echo "$file"
foo bar,spam.egg

$ rename -n 's/[^a-zA-Z0-9_-]//' "$file"
foo bar,spam.egg renamed as foobar,spam.egg

$ rename -n 's/[^a-zA-Z0-9_-]//g' "$file"
foo bar,spam.egg renamed as foobarspamegg

You can do this will bash alone, with parameter expansion:

  • For removing everything except a-zA-Z0-9_- from file names, assuming variable file contains the filename, using character class [:alnum:] to match all alphabetic characters and digits from current locale:

    "${file//[^[:alnum:]_-]/}"
    

    or explicitly, change the LC_COLLATE to C:

    "${file//[^a-zA-Z0-9_-]/}"
    

Example:

$ file='foo bar,spam.egg'

$ echo "${file//[^[:alnum:]_-]/}"
foobarspamegg