Do not parse filenames with
sed! The output of
echo "$file" may not be reliable.
rename. On 17.10 you need to install it first
sudo apt install rename
rename -n -- 's/[^-A-Za-z0-9_ .]/_/g' *
-n after testing to actually rename the files
-- end-of-options in case any file begins with
[^-A-Za-z0-9_ .] characters we do not want to replace - put
- first or last so it can't indicate a range (it is treated literally in these positions).
- Spaces can be included in the class
. is treated literally (in other regex contexts it stands for any character and needs to be escaped).
This also works in
$ echo 'trip: hill' | sed 's/[^-A-Za-z0-9 _.]/_/g'
If I add a space to the end in your version, I get an error:
$ echo 'trip: hill' | sed -e 's/[^A-Za-z0-9._- ]/_/g'
sed: -e expression #1, char 22: Invalid range end
- at the end, it works:
$ echo 'trip: hill' | sed -e 's/[^A-Za-z0-9._ -]/_/g'
So perhaps the position of the hyphen caused your problem when you added the space. But the advice not to parse filenames stands!