Linux rename Command

Linux Command Encyclopedia


renameThe command is a practical tool in Linux systems for batch renaming files. By using regular expressions or simple string replacement, it can efficiently rename multiple files, making it especially suitable for scenarios that require batch processing of file names.


Basic Syntax

renameThe basic syntax format of the command is as follows:

rename [选项] '表达式' 文件...

Parameter Description

  • Expression: Specifies the regular expression or replacement string for the filename conversion rule
  • File: The target files to be renamed, supports wildcards (e.g.*.txt)

Common Options

Option Description
-v Display detailed operation information (verbose)
-n Simulate operation, do not actually perform renaming (dry-run)
-f Force overwrite existing files
-h Display help information

Usage Examples

1. Simple String Replacement

Change all in the current directory.htmlfile extension to.php:

rename 's/.html$/.php/' *.html

Code Analysis:

  • s/Indicates the start of the replacement operation
  • .html$Matches filenames ending with.htmlfilenames ending with ($represents end of line)
  • /.php/Replace with.phpextension

2. Add Prefix

For all.txtfiles addbackup_prefix:

rename 's/^/backup_/' *.txt

3. Delete Specific Characters

Remove all spaces in filenames:

rename 's/ //g' *

Note:gIndicates global replacement (all matches)

4. Case Conversion

Change all.jpgfile extensions to uppercase:

rename 's/.jpg$/.JPG/' *.jpg

Advanced Usage

1. Using Variables and Complex Replacement

rename 's/(d+)/sprintf("%03d", $1)/e' *.png

Function: Format the digit sequence in filenames to 3 digits (e.g.1.png → 001.png)

2. Conditional Renaming

rename 'if (/.jpeg$/) { s/.jpeg$/.jpg/ }' *

Function: Only for.jpegfiles, modify the extension


Precautions

  1. Back up important files: Before performing batch renaming, it is recommended to first use-noption to test
  2. Regular expression syntax: The implementation of different Linux distributions'renameimplementation may differ
  3. Special character handling: If filenames contain special characters, they need to be escaped
  4. Permission issues: Ensure you have write permission to the target files

Alternatives

If the system does not have therenamecommand pre-installed, you can use the following alternative methods:

1. Usemvwith a loop

Example

for file in *.html; do
    mv "$file" "${file%.html}.php"
done

2. Install the Perl version of rename

Example

# Ubuntu/Debian
sudo apt install rename

# CentOS/RHEL
sudo yum install prename

Summary

renameThe command is a powerful tool for Linux file management. By mastering its regular expression syntax, you can efficiently complete various complex batch renaming tasks. It is recommended to practice starting with simple replacements and gradually master more advanced usage.


Linux Command Encyclopedia

Other Extensions