img

UNIX Command To Rename A File

September 8, 2019

How do I rename a file in UNIX using command line options?

The mv is a Unix command that renames one or more files or directories. The original filename or directory name is no longer accessible. Write permission is required on all directories and files being modified. Use the mv command to:

  • Moves a file (i.e. gives it a different name).
  • Rename a file.

mv command syntax

You need to use the mv command to rename a file as follows:

mv old-file-name new-file-name
mv file1 file2
mv source target
mv [options] source target

Examples

Open the terminal (bash shell prompt) and type the following command to list file names:

ls 
ls -l

ls
ls -l

In this example, rename a file called data.txt to letters.txt, enter:

mv data.txt letters.txt
ls -l letters.txt

mv data.txt letters.txt
ls -l letters.txt

File is renamed so the following command will display an error on screen:

ls -l data.txt

ls -l data.txt

Outputs:

ls: cannot access data.txt: No such file or directory

The following would rename a file called foo to bar, while keeping it in the current directory:

mv foo bar

mv foo bar

Rename a directory/folder Unix command

The following would rename a directory (folder) called dir1 to dir2, while keeping it in the current directory:

mv dir1 dir2

mv dir1 dir2

Move a file/folder to an existing directory

The following would move a file named resume.txt, without changing its name, to an existing subdirectory called /home/nixcraft/Documents/

mv resume.txt /home/nixcraft/Documents/
 
## verify new file location with ls -l command ##
ls -l /home/nixcraft/Documents/

mv resume.txt /home/nixcraft/Documents/ ## verify new file location with ls -l command ##
ls -l /home/nixcraft/Documents/

Suggested Readings:

Type the following command to read mv command man page:
man mv

Posted by: SXI ADMIN

The author is the creator of SXI LLC and a seasoned sysadmin, DevOps engineer, and a trainer for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin, Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.

Article Tags:
Article Categories:
How To

Comments are closed.