Home > Linux, Varie ed eventuali > Linux: how to remove a file when the filename begins with a dash

Linux: how to remove a file when the filename begins with a dash

Did you ever try to remove a file when the filename begins with a dash (e.g. -1.html)?

This operation can be a real pain and it’s a little bit frustrating because you’ll not be able to remove the file using the standard “rm” command. It seems that it’s impossible to escape the dash sign using the backslash, so something like

rm -v \-1.html

won’t work at all.

Maybe you are asking yourself why a filename should start with the dash sign… Ok, it happened to me while developing a small bash script to generate some html pages from a CSV file. I wanted the file name to be extracted from the data and I needed to sanitize it a little bit. So I needed to remove all the strange characters and the spaces replacing everything with a dash sign (this is for SEO…). While experimenting the script, I noticed that the temp folder where the script was working was filled with dash starting filenames….

The trick is quite simple and it’s already available on other sites; it’s just a matter of searching with Google!

You can remove a file using it’s inode number. So the full procedure is:

cd /somewhere/on/your/server
ls -ila *

look for the inode number and then

find ./ -inum INODE_NUMBER -ok rm '{}' \;

Let’s do this just for testing:

[root@xxxxxx tmp]# touch \\-testfile.html
[root@xxxxxx tmp]# ls -ila *.html
2580274 -rw-r--r--  1 root root 0 24 lug 11:39 \-testfile.html
[root@xxxxxx tmp]# find ./ -inum 2580274 -ok rm '{}' \;
< rm ... ./\-testfile.html > ? y

Hope this helps

Roberto Cespa Linux, Varie ed eventuali , , , , , , , , , ,

  1. 18 febbraio 2010 a 17:25 | #1

    I think you can just put a path on it: rm ./-1.html

  2. 18 febbraio 2010 a 17:40 | #2
  1. Nessun trackback ancora...