Command Line

How to Rename Files and Directories in Linux: From Basics to Batch Operations

How to Rename Files and Directories in Linux: From Basics to Batch Operations

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 destination

Renaming a Single File

To rename file1.txt to file2.txt:

mv file1.txt file2.txt

Batch Renaming with mv

While mv is designed for single operations, you can combine it with other commands for batch renaming:

  1. Using a Bash for loop:
for f in *.html; do
    mv -- "$f" "${f%.html}.php"
done
  1. 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-rename or yaourt -S perl-rename

Basic Syntax

rename [OPTIONS] perlexpr files

Common rename Operations

  1. Change file extensions:
   rename 's/.html/.php/' *.html
  1. Preview changes without applying:
   rename -n 's/.html/.php/' *.html
  1. Replace spaces with underscores:
   rename 'y/ /_/' *
  1. Convert filenames to lowercase:
   rename 'y/A-Z/a-z/' *
  1. Convert filenames to uppercase:
   rename 'y/a-z/A-Z/' *

Pro 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 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!

Suggested Articles

Leave a Reply

Your email address will not be published. Required fields are marked *