How to remove files with special characters in Linux

I recently found myself having to remove a file with special characters. Using rm only gave me “rm: unrecognized option”, which forced me to take off the gloves.

To remove a file with dashes, slashes or other special characters, the easiest way is to access the file using its inode. To get the inode of a file, just do a ls -li. When you have that number, use find to delete the file using the following command:

find . -inum [inode] -exec rm -i {} \;

Good hunting!

9 thoughts on “How to remove files with special characters in Linux”

  1. rm has an option built-in for doing this (see the man page):


    To remove a file whose name starts with a `-', for example `-foo', use one of these commands:

    rm -- -foo
    rm ./-foo

    so,


    $ rm -- -\,my\?\ funky.file\$name

  2. I don’t think Linux allows a ‘/’ in a filename. ‘\’ is ok:

    ~/tmp2|$ touch — file/foo
    touch: file/foo: No such file or directory
    ~/tmp2|$ touch “file/foo”
    touch: file/foo: No such file or directory
    ~/tmp2|$ touch — file\/foo
    touch: file/foo: No such file or directory
    ~/tmp2|$ touch “file\/foo”
    touch: file\/foo: No such file or directory
    ~/tmp2|$ touch — ‘file/foo’
    touch: file/foo: No such file or directory
    ~/tmp2|$ touch ‘file/foo’
    touch: file/foo: No such file or directory
    ~/tmp2|$ touch file\foo
    ~/tmp2|$ ls
    filefoo
    ~/tmp2|$ touch file\\foo
    ~/tmp2|$ ls
    file\foo filefoo

    An exception is a unicode ‘/’ maybe.

  3. Mac OS for instance, seems to be able to handle using slashes in filenames. And if creating a file on say a NFS mount, and using that share in Linux could make things interesting.

    1. Interesting, FWIW, all the tests I did above were in Terminal on a Macbook. Didn’t think to try from Finder.

      But… here’s your answer… OS X saves the ‘/’ as ‘:’ on the file system, so it’s no problem:

      ~/tmp2|$ ls -l
      total 8
      -rw-r–r–@ 1 ben staff 317 Aug 31 09:35 file:foo::bar.rtf

      ~/tmp2|$ rm file:foo::bar.rtf

      ~/tmp2|$ ls -l
      ~/tmp2|$

    2. Interesting indeed. I just tried using Finder, assuming that it’s the same as using the terminal.

      On a side note, he//o is converted to he��o? when saved to a linux server over smb.

Leave a Reply