Renaming files is a fundamental task in Linux, whether you’re organizing your personal documents or managing server data. While renaming a single file is straightforward, batch renaming can be more challenging. This guide will walk you through using the mv and rename commands to efficiently manage file names in Linux.
The mv Command: Simple and Versatile
The mv command is your go-to tool for basic file renaming and moving. Its syntax is:
mv [OPTIONS] source destinationRenaming a Single File
To rename file1.txt to file2.txt:
mv file1.txt file2.txtBatch Renaming with mv
While mv is designed for single operations, you can combine it with other commands for batch renaming:
- Using a Bash for loop:
for f in *.html; do
mv -- "$f" "${f%.html}.php"
done- Combining with
find:
find . -depth -name "*.html" -exec sh -c 'f="{}"; mv -- "$f" "${f%.html}.php"' \;Both examples change all .html files to .php in the current directory.
The rename Command: Power User’s Choice
For more complex renaming tasks, the rename command (Perl version) offers advanced functionality using regular expressions.
Installing rename
- Ubuntu/Debian:
sudo apt install rename - CentOS/Fedora:
sudo yum install prename - Arch Linux:
yay perl-renameoryaourt -S perl-rename
Basic Syntax
rename [OPTIONS] perlexpr filesCommon rename Operations
- Change file extensions:
rename 's/.html/.php/' *.html- Preview changes without applying:
rename -n 's/.html/.php/' *.html- Replace spaces with underscores:
rename 'y/ /_/' *- Convert filenames to lowercase:
rename 'y/A-Z/a-z/' *- Convert filenames to uppercase:
rename 'y/a-z/A-Z/' *Pro Tips
- Use
-fto overwrite existing files:rename -f 's/.html/.php/' *.html - The
renamecommand uses Perl regular expressions, offering powerful pattern matching capabilities.
Conclusion
Mastering file renaming in Linux can significantly boost your productivity. While mv is perfect for simple tasks, rename shines in complex batch operations. For those new to the command line, GUI tools like Métamorphose offer a user-friendly alternative.
Remember to always double-check your commands, especially when dealing with important files. Practice in a safe directory first to gain confidence.
We hope this guide helps streamline your file management tasks in Linux. Feel free to leave comments or questions below!
