Renaming Files in the Terminal (CLI)

Renaming files in the terminal can be a quick and efficient way to manage your file system, especially when dealing with multiple files or when you’re working on a remote server without a graphical interface. This method also allows you to create scripts that can automate batch file renaming and is useful when you need to rename files according to specific patterns or rules.

In most Unix-like operating systems, such as Linux and macOS, the command used to rename files is mv, which stands for move. Despite its primary function to move files, it’s also widely used to rename files because renaming is effectively moving a file from one name to another within the same directory.

Setup for this tutorial(If you want to follow along):

On MacOs or Linux, you can open your terminal by pressing command + space and typing terminal, selecting the terminal app and then pressing enter.

In your termainal, run the following commands to setup a directory for this tutorial: In MacOS or Linux:

mkdir mv-tutorial
cd mv-tutorial
touch oldfilename.txt
mv command in bash.

How to Rename a File:

Open your terminal (or command line interface).

To rename a single file, use the mv command followed by the current filename and then the new filename:

mv oldfilename.txt newfilename.txt

To verify the file was renamed, you can use the ls command to list the files in the current directory:

ls
mv command in bash.

This will rename the file oldfilename.txt to newfilename.txt.

Batch Renaming:

To rename multiple files, you can use a loop or find a pattern to apply the renaming. For example, if you want to add a prefix to multiple .txt files, you could do something like:

for file in *.txt; do
  mv "$file" "prefix-${file}"
done

This will add the word prefix- to the beginning of every file in the current directory with a .txt extension.

Renaming with Confirmation:

If you’re unsure and want to confirm before actually renaming each file, you can do this interactively with the -i option:

mv -i oldfilename.txt newfilename.txt

This will prompt you before overwriting any files.

Caution:

Double-check the filenames when you use the mv command, as it will immediately perform the action without any undo function. If a file with the name of the target already exists, it will be overwritten without warning unless you use the -i option.

Always ensure that your new filename does not clash with existing files or you may lose data. Regular backups and careful checking are good practices to prevent any accidental loss.

By using the terminal to rename files, you can quickly make changes to your file system without the need for a graphical user interface, and you can easily automate this process to apply complex renaming rules to many files at once.