Can't rename a file the name of which starts with a hyphen

38

4

I'm trying to rename a file with a hyphen at the beginning of its name and both this:

mv -example-file-name example-file-name

and this:

mv '-example-file-name' example-file-name

result in:

mv: invalid option -- 'e'

Desmond Hume

Posted 2012-11-25T14:55:37.453

Reputation: 1 870

In case anyone wonders: mv *example-file-name example-file-name has the same problem, because filename expansion (AKA globbing) happens before mv is called. – Walter Tross – 2017-02-10T13:36:17.390

1Either use the relative path of the file (./tmp/-example), the full path (/home/a/tmp/-example) or tell mv that you're done giving options with -- and that what follows are file names. – Ярослав Рахматуллин – 2012-11-25T15:30:01.950

Answers

57

Most GNU/Linux commands allow a -- option to indicate end of options so that subsequent - prefixed words are not treated as options.

  mv -- -example-file-name example-file-name

A small test

$ touch -- -example
$ ls -l -- *ample
-rw-r--r-- 1 rgb rgb 0 Nov 25 09:57 -example
$ mv -- -example example
$

RedGrittyBrick

Posted 2012-11-25T14:55:37.453

Reputation: 70 632

This resolves the same problem for rename, too. (at least the version that works like rename [options] <expression> <replacement> <file>..., whichever one that is.) – underscore_d – 2016-10-10T08:48:31.010

Damn, BSD / Mac OS X mv doesn't have this :( – Sridhar Sarnobat – 2017-07-25T04:03:16.063

19

RedGrittyBrick's answer is very good. Another option is:

mv ./-example-file-name example-file-name

A small test:

$ touch ./-example
$ ls -l ./*ample
-rw-r--r-- 1 me me 0 Nov 25 16:02 ./-example
$ mv ./-example example
$ ls -l ./*ample
-rw-r--r-- 1 me me 0 Nov 25 16:02 ./example

gniourf_gniourf

Posted 2012-11-25T14:55:37.453

Reputation: 1 882

very nice workaround, this never occurred to me. And unlike the accepted answer, this will work on BSD / Mac OS X – Sridhar Sarnobat – 2017-07-25T04:11:34.593

Thats a little more catchy than --. – Corni – 2018-10-15T06:43:56.897

-1

You can use this:

rename -- "s/\-//g" *

that it can rename all file :) if your file name :

-ng--sh-ay-01[------------]-FLV

after run code, your file name become:

ngshay01[]FLV

k-five

Posted 2012-11-25T14:55:37.453

Reputation: 1

1The other approaches (the one by RedGrittyBrick, and gniourf_gniourf) are more likely to work with several other commands. – TOOGAM – 2015-12-17T21:57:02.800

-1

This trick works for me in times of desperation. YMMV

rename \- '' *

You have to escape the hyphen for rename to recognize it. Why rename doesn't respect single quotes or offer an override of some kind is beyond me.

This is the only method I've seen that reliably handles a leading hyphen using rename. I agree with the other posts on using mv, but if you can't use mv for any reason, this works.

Alex Z

Posted 2012-11-25T14:55:37.453

Reputation: 1