Ubuntu – How to Perform operations on files or directories with dashes or hyphens?

bashnaming conventions

My question is that I was trying to rename a file named 12F-XYZ.pdf to 13F-XYX_ABX.pdf.

Now the problem that rises is that both of hyphen the original and the required names have hyphens I know that for spaces we use \ to overcome the problem but what can we do in the case of hyphen or any other character that can actually cause the problem like this with not only rename command but any other command.

Best Answer

  • As 'David Foerster' has pointed out hyphen(-) is not treated specially by 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 would be a very good read for you.

    EDIT: As 'muru' pointed out you would have problem in case a leading hyphen. In that case you can use any one of the following:

    mv -- foo.bar -foo.bar
    mv foo.bar ./-foo.bar

    The -- indicates the end of switch for the previous command (in this case mv). Also note that not all commands supports -- so you would be better using the second option (./-foo.bar).