Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Linux rename command

Linux rename command

Linux Command Reference Linux Command Reference


rename command is a practical tool in Linux for batch-renaming files. By using regular expressions or simple string replacements, it can efficiently rename multiple files, making it especially suited to scenarios that require batch processing of filenames.


Basic Syntax

rename The basic syntax of the command is as follows:

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

Parameter Description


Common options

Option Description
-v display detailed operation information (verbose)
-n simulate the run without actually renaming (dry-run)
-f force overwrite of existing files
-h Display help information

Usage examples

1. Simple string replacement

Rename all .html files in the current directory with the extension .php:

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

Code Analysis:

2. Add a prefix

Add a prefix to all .txt files backup_ prefix:

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

3. Delete specific characters

Delete all spaces in filenames:

rename 's/ //g' *

Note:g indicates a global replacement (all matches)

4. Case conversion

Change the extension of all .jpg files to uppercase:

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


Advanced usage

1. Using variables and complex replacements

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

Function: format numeric sequences in filenames to 3 digits (such as 1.png → 001.png)

2. Conditional renaming

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

Function: only modify the extension of .jpeg files


Notes

  1. Back up important files: before performing a batch rename, it is recommended to first use the -n option to test
  2. Regular expression syntax: different Linux distributions may have different rename implementations
  3. Special Character Handling: escape special characters when filenames contain them
  4. Permission issues: ensure you have write permission on the target files

Alternatives

If the system does not have the rename command preinstalled, you can use the following alternatives:

1. Using mv combined with 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

rename command is a powerful tool for Linux file management. By mastering its regular expression syntax, you can efficiently accomplish a wide variety of complex batch-renaming tasks. It is recommended to start practicing with simple replacements and gradually work your way up to more advanced usage.


Linux Command Reference Linux Command Reference