How can I safely perform operations on files or directories with dashes or hyphens?
Solution 1:
As David Foerster pointed out in a comment, hyphens (-) are not treated specially by the shell. So as far as your example is concerned you can simply do:
mv 12F-XYZ.pdf 13F-XYX_ABX.pdf
But if you have a space or literal escape character (backslash) or any other that needs to be escaped, you can escape those with either the escape character i.e. \
or put the whole name inside quotes '
'
so that the content inside the quotes is treated literally.
Here is an example:
mv 12F-XYZ.pdf 50M -XYZ.pdf ##Wrong
mv 12F-XYZ.pdf 50M\ -XYZ.pdf ##Right
mv 12F-XYZ.pdf '50M -XYZ.pdf' ##Right
A rule of thumb would be to escape it while in doubt. This article on special characters would be a very good read for you.
As muru pointed out in comments, you could have problem in case of a leading hyphen as many commands treat arguments beginning with a hyphen as options. In that case you can use either of the following:
mv -- foo.bar -foo.bar
mv foo.bar ./-foo.bar
The --
indicates the end of switches for the previous command (in this case mv
). Not all commands support --
so using the second option (./-foo.bar
) would be more reliable.