Renaming files is a fundamental task in Linux systems. While it’s straightforward for single files, batch renaming can be challenging, especially for newcomers. This guide will walk you through using the mv
and rename
commands to efficiently manage file names in Linux.
The mv Command: Basic File Renaming
The mv
(move) command is versatile, used for both moving and renaming files. Its basic syntax is:
mv [OPTIONS] source destination
To rename a single file:
mv oldname.txt newname.txt
Renaming Multiple Files with mv
While mv
is designed for single file operations, it can be combined with other commands for batch renaming. Here are two approaches:
- Using a Bash for loop:
for f in *.html; do
mv -- "$f" "${f%.html}.php"
done
- Combining with the
find
command:
find . -depth -name "*.html" -exec sh -c 'f="{}"; mv -- "$f" "${f%.html}.php"' \;
These methods change all .html
files to .php
in the current directory.
The rename Command: Powerful Batch Renaming
The rename
command, specifically its Perl version, offers more advanced functionality for batch renaming using regular expressions.
Installing rename
- Ubuntu/Debian:
sudo apt install rename
- CentOS/Fedora:
sudo yum install prename
- Arch Linux:
yay perl-rename
oryaourt -S perl-rename
Basic rename Syntax
rename [OPTIONS] perlexpr files
Common 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/' *
rename Tips
- Use
-f
to overwrite existing files:rename -f 's/.html/.php/' *.html
- The
rename
command uses Perl regular expressions, offering powerful pattern matching capabilities.
Conclusion
Mastering file renaming in Linux enhances your productivity and file management skills. While mv
is great for simple operations, rename
offers powerful batch processing capabilities. For those preferring graphical interfaces, tools like Métamorphose provide user-friendly alternatives.
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!