If you need to rename a single file in Linux, the mv (move) command works perfectly (e.g., mv old.txt new.txt). However, if you need to rename 500 photographs, or change the file extension of 2,000 HTML files from .htm to .html, using the mv command one by one is impossible.
To batch-rename hundreds of files instantly, you need to use the powerful rename command.
Installing the rename Command
Unlike mv, the rename command is a Perl script that is not always installed on every Linux distribution by default.
To check if you have it, simply type rename --version in your terminal. If it says \”command not found\”, you must install it.
- On Ubuntu/Debian:
sudo apt install rename - On CentOS/RHEL:
sudo yum install prename
Understanding the Syntax (Regular Expressions)
The rename command uses Perl Regular Expressions (Regex) to find and replace text within filenames. This makes it incredibly powerful, but the syntax can look intimidating to beginners.
The Basic Structure: rename 's/old_text/new_text/' *.files
- s/: Stands for “substitute”. It tells the command to search and replace.
- old_text: The exact string of text you want to find in the filename.
- new_text: What you want to replace it with.
- *.files: The target files you want the command to run against.
Example 1: Changing File Extensions
Imagine you have a directory full of images ending in .jpeg, but your web developer requested that they all end in .jpg.
Navigate to the directory and run this command:
rename 's/\\.jpeg$/\\.jpg/' *.jpeg
(Note: The backslash before the dot tells Linux that it is a literal period, and the dollar sign at the end tells Linux to only look at the very end of the filename).
Instantly, every single .jpeg file in the folder will be renamed to .jpg.
Example 2: Removing Spaces from Filenames
Linux hates spaces in filenames. If you download a batch of files named like “Vacation Photo 01.jpg”, you will have to put quotes around them every time you use them in the terminal.
You can use the rename command to instantly replace all empty spaces with underscores (_).
rename 's/ /_/g' *
(Note: The “g” at the very end stands for “global”, meaning it will replace every single space it finds in the filename, not just the first one).
Your file will instantly become “Vacation_Photo_01.jpg”.
The \”Dry Run\” Safety Feature
Because the rename command acts instantly across hundreds of files, making a typo in your Regex can destroy a directory.
Before running a massive rename operation, always use the -n (no action/dry run) flag.
rename -n 's/ /_/g' *
This will not actually change any files. Instead, it will print a list to your terminal showing exactly what would happen if you ran the command for real (e.g., 'Vacation Photo.jpg' would be renamed to 'Vacation_Photo.jpg'). If the output looks correct, run the command again without the -n flag to make it permanent.