While dealing with Linux systems, one of the tasks you’re going to encounter is to rename files. The mv command, which stands for ‘move’ is what we use to rename filenames on the Linux terminal.
The mv command can be used in all Linux distributions and it’s popular for being simple and versatile.
Basic Syntax of the mv Command
The mv command has a straightforward syntax, which is demonstrated as follows:
mv old_filename new_filename
From the above, you can type the mv command space followed by the old filename space, followed by the new filename. The old_filename could be the current name of the file you want to rename and new_filename could be the new name you want to give the file.
Examples of using the mv command to rename files.
Let’s say you have a file called report.txt and you want to rename it to summary.txt, you would use the following command:
mv report.txt summary.txt
Assuming you have a text file named notes.txt and you want to rename it to meeting_notes.txt, here is how you would go about it:
mv notes.txt meeting_notes.txt
After running the above command, the file notes.txt no longer exists, and a new file called meeting_notes.txt takes its place.
Renaming Files in Different Directories
You can also use the mv command to move files across directories. For example, let’s say you have a file in one directory that you want to move and rename in another directory, the command would look as follows:
mv /home/user/old_directory/file.txt /home/user/new_directory/renamed_file.txt
The above command will move file.txt from the old_directory and place it in new_directory with the new name renamed_file.txt.
Handling File Overwrites using the mv command
By default, the mv command overwrites any existing file with the same name without prompting you. For example, if you run the following command and there’s already a file named renamed_file.txt, it will be replaced without warning:
mv file.txt renamed_file.txt
You can also avoid accidental overwriting of filenames by using the -i option (interactive mode):
mv -i old_filename new_filename
Using the -i option will prompt you before overwriting an existing file.
Renaming Directories using the mv command
The mv command is not limited to renaming files only—you can rename directories as well, and the syntax is the same:
mv old_directory new_directory
The above command renames old_directory to new_directory without changing its contents or location.