Filenames with special characters

Some special characters (generally whitespace or punctuation such as [!@#$%^&*()-\<>]) have special meaning in shell commands.

If you use these characters in filenames, you can end up having problems trying to open, rename or even delete them.

There are two main cases:

The filename has hidden characters
Usually the hidden character is one or more spaces, sometimes it's a control character. You can amuse yourself by guessing the number of spaces and enclosing the filename in quotes, e.g. rm "foo " Or you can try to force a match on the filename by using the file-completion feature of your shell (ie. type in the first few characters of the filename and then hit the TAB key), or using the wildcard *.
The filename has shell metacharacters
The classic case is a filename starting with -. You can try referring to the file as ./-foo, or escape the metacharacter with a \, or use the '-' or '--' flag in the rm command (use man rm to see which is installed on your system), which forces rm to take whatever follows as the name of a file to be removed.

If none of these work then your best bet is to avoid trying to name the file yourself. Use rm -ri . to make Unix find the file for you, and with great care say 'y' to the file you want removed, and 'n' to all the others.

A less dangerous method is to refer to the file by its inode number, which is its real name as far as Unix is concerned anyway. Use ls -i to find out the inode number, and then use

find . -inum inode -ok rm '{}' \;

The advantage of this method is that it also allows you to rename the file if you actually want to keep it, but have been unable to access it because of the funny characters.

To rename the file, use

find . -inum inode -ok mv '{}' new-file-name \;

If you don't want the -ok safety check, use -exec instead.

Last edited by jbc 19/02/2018

Tags for this page:

delete, rename, filename, special, hyphen