At first it might not be obvious, but you can easily use the mv command to rename files in Linux. From the terminal, this Linux command can be used to move a file or directory from one location to another or to rename a file or directory. It might also be used to move a file to a different directory whilst renaming it.
Table of Contents
How to rename files in Linux
To rename a file using the mv command in Linux:
- Open the terminal. (Ctrl+Alt+T) for Ubuntu/Debian Linux.
- Using the cd command, change directory to the location that contains the file you want to rename.
- To rename the file, type sudo mv <filename> followed by the <new filename> and then press Enter to execute the command.
sudo mv name.txt newname.txt
The mv command can also be used to move a file to a different directory while renaming it during the move.
How to rename a file while moving in Linux
To rename file in terminal while moving it to another directory:
- Open a terminal.
- Type sudo mv <filename> <directory/> to move it to, followed by <new filename>
sudo mv name.txt newdir/newname.txt
Or you can even use the mv command to rename a folder in Linux.
How to rename a folder in Linux
To rename folder in Linux:
- Open a terminal.
- Type sudo mv <current folder name> followed by <name for new folder>
sudo mv folder newfolder
mv command options
Here are some common options you can use with the mv command:
-i : Prompt the user before overwriting an existing file.
-v : Display the name of each file or directory as it is being moved.
-u : Move only when the source file is newer than the destination file or when the destination file does not exist.
-f : Force move, overwrite any existing destination files without prompting.
The syntax is as follows:
mv [options] source destination
WARNING: Be cautious when renaming files in Linux, as it can result in unintended consequences if done incorrectly. Always be sure to back up important files before experimenting and attempting to rename them.
If you found this method to rename files in Linux useful, you might also take interest in learning how to use Loop Commands in Shell or Batch Scripts.