Filenames with special characters

Sooner or later everyone makes a slip and ends up giving a file a dumb name that seems to make it impossible to delete the file. Trying to rm it just returns the error message no such file or directory. But as you should know by now, in Unix there is always a way. 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 24/07/2017

Tags for this page:

delete, rename, filename, special, hyphen