Rename a file in Linux is done by using mv(move) command. The name of this command is bit misleading and many newcomers to Linux/Unix feel that the files are moved but not renamed. That is true to some extent if the files are moved from one directory to another directory. But if the files are moved within directory they can be treated as renaming those files. This is a bit tricky to understand. In other words, mv command can do both renaming files/folders and move files/folders from one location to other.

Syntax for mv command

mv oldname newname

Let’s learn mv command with some examples for better understanding it.

Example1: Rename a file from file1.txt to abc1.txt

mv file1.txt abc1.txt

Example2: Rename a folder from folder1 to abcfolder

mv folder1 abcfolder

Example3: Move all text files from /abc to /newabc

mv /abc/*.txt /newabc

Example4: Move /abc/read/ folder to /newread folder.

mv /abc/read /newread

Example5: How to rename files with spaces in the filenames. We can use escape char \ for renaming files. Rename file “abc\ cde.txt” file to abc_cde.txt

mv abc\ cde.txt abc_cde.txt

Example6: Rename files with special characters like *, $ etc.

File: abc*cde.txt

mv abc*cde.txt abc_cde.txt

Example7: Rename files which have – at starting of the filename

File: -abc.txt

Note: Many commands consider “-” as options, even mv command do the same thing. if you have file names which start – or — how we can rename them. Let us start using normal mv command and see what the error we get

mv -abc.txt cde.txt
mv: invalid option -- 'a'
Try `mv --help' for more information.

Let us try with our escape char “”

mv -abc.txt cde.txt
mv: invalid option -- 'a'
Try `mv --help' for more information.

We get the same issue, then how to resolve this issue?

We have inbuilt options in most of the commands which can inform the command that options are completed and there are no more options left and only files are left, that operator is “–“. Use below command when you want to rename files which start with – or — in the file name

mv -- -abc.txt cde.txt

or

You can try below option too…

mv ./-abc.txt cde.txt

For renaming multiple files we have to use a shell script, Please click here to know how to write a shell script and use rename command to rename multiple files.

The following two tabs change content below.
Mr Surendra Anne is from Vijayawada, Andhra Pradesh, India. He is a Linux/Open source supporter who believes in Hard work, A down to earth person, Likes to share knowledge with others, Loves dogs, Likes photography. He works as Devops Engineer with Taggle systems, an IOT automatic water metering company, Sydney . You can contact him at surendra (@) linuxnix dot com.