Linux

Linux Rename File Starting with Dash

While naming a file, it is a common and recommended practice to not start or end a file name with a hyphen (dash), space, underscore, and period (dot). However, sometimes you can mistakenly start a file name with a dash. Although it’s fine, but this naming can be a little problematic as the options (switches) of almost all Linux commands start with a dash. In this case, if you pass that file name starting with a dash to a Linux command, it will be treated as the command option (switch) and will most likely fail. The most common problem occurs when you try to rename this file to remove the dash. However, this will not be a problem for you anymore as we are going to show you how to rename a file starting with a dash in a Linux OS.

Note: The method shown here has been tested on Ubuntu 20.04 LTS. However, it can be followed in any other Linux distribution.

Let’s first show you what happens when you rename a file starting with a dash. The output below shows that the mv (rename) command is treating the non-option argument (filename “-doc”) as the command option and giving the “invalid option” error.

To view all the files starting with a dash in the current directory, use the command below:

Rename File Starting with Dash

There are two ways to rename a file that starts with a dash. Let’s discuss both of them.

Method 1

To rename a file starting with a dash, prepend “./” to the file name where the “.” indicates the current Terminal directory and “/” indicates that the name points to a file in the current directory. The purpose of “./” before the filename is to hide the dash from the command.

For instance, to rename a file named “-doc” inside the current directory to “mydoc”, the command would be:

This will rename the file to “mydoc”.

If a file to rename is in another directory, specify the file’s path. For instance, to rename a file “-doc” located in the ~/Documents directory to “mydoc”, the command would be:

$ sudo mv ~/Documents/-doc ~/Documents/mydoc

Method 2

Another way to rename a file starting with a dash is to use the double-dash “–” before the filename. The “–” is used in the Linux commands to indicate the end of options and to disable further option processing. After “–” nothing is taken as an option. This is done to terminate the option processing. Otherwise, the command will treat the non-option argument as options (flags) and will fail. Therefore, you will need to use “–” when the non-option argument begins with a dash.

To rename a file “-doc” to “mydoc”, use “–” before the filename as follows:

This will rename the file to “mydoc”.

That’s it. In this post, we showed you two ways to rename a file starting with a dash in Linux. To know more about the mv (move and rename) command, visit its Man page.

Source link

Related Articles

Leave a Reply

Your email address will not be published.

Back to top button