rename Command in Linux: Batch Rename Files with Regex
Learn rename command in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.
10 min read
Learn rename command in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.
- What rename Does and When to Use It
- Availability and Installation Across Linux Distributions
- Command Syntax, Arguments, and Exit Status Codes
While the standard mv command excels at renaming single files or moving paths across directories, executing batch filename modifications across hundreds of files requires the powerful rename command in linux. By combining Perl-compatible regular expressions (PCRE) with directory traversal, rename transforms bulk file manipulation into concise, one-line commands.
The rename command in Linux allows you to batch rename multiple files and directories using Perl regular expressions or simple string substitution. Run rename -n 's/\.jpeg$/\.jpg/' *.jpeg to preview changes safely with a dry-run, and remove the -n option to commit the bulk filename modifications across all matching files.
System administrators, software developers, and media engineers frequently encounter scenarios where file extensions must be standardized (e.g., converting .jpeg to .jpg), spaces replaced with underscores, date prefixes inserted, or mixed-case filenames converted entirely to lowercase. Performing these operations with ad-hoc shell loops can be slow and error-prone, whereas rename executes atomic, in-place filename transformations safely.
In this comprehensive guide, we contrast the two distinct implementations of rename found in the Linux ecosystem (Perl File::Rename versus C util-linux rename), review regular expression substitution syntax, detail the critical dry-run safeguard, and establish robust batch renaming workflows.
What rename Does and When to Use It
Under the hood, the Linux Virtual File System (VFS) represents a file's name not inside its inode metadata, but as a directory entry (dentry) that maps a UTF-8 character string to a specific inode number. When rename operates on files within the same filesystem, it issues the renameat2(2) system call. The kernel atomically unlinks the old dentry and establishes the new dentry pointing to the same existing inode without moving, copying, or reallocating the underlying data blocks.
In the Perl implementation (File::Rename, standard on Debian, Ubuntu, and Linux Mint), the binary compiles the user's regular expression string (e.g., s/pattern/replacement/flags) into a Perl code closure and executes it against each matching filename string. If the expression alters the string, rename evaluates the target path. If the destination filename already exists, rename protects against accidental overwrites by failing unless the -f (force) option is explicitly passed.
At the operating system level, rename (distributed in rename (Perl File::Rename) / util-linux) interfaces with the Linux kernel through standard C library system calls and virtual filesystems. Understanding how rename resolves file descriptors, kernel structures, and exit status codes helps system administrators predict performance on high-load production servers.
Availability and Installation Across Linux Distributions
The rename utility is packaged in rename (Perl File::Rename) / util-linux across mainstream Linux distributions. It is pre-installed on standard Ubuntu, Debian, RHEL, Rocky Linux, AlmaLinux, Fedora, and Arch Linux systems, while minimal container images may require manual installation:
Before running administrative tasks or automation scripts, verify whether rename is installed and inspect which binary path and version your shell resolves:
type -a rename
rename --version 2>/dev/null || man -f rename
# Illustrative output (reviewed against documentation)
rename is /usr/bin/rename
rename (rename (Perl File::Rename) / util-linux)
# Debian / Ubuntu
sudo apt-get update && sudo apt-get install -y rename
# RHEL / Rocky / AlmaLinux / Fedora
sudo dnf install -y prename
# Arch Linux
sudo pacman -S --noconfirm perl-rename
# Alpine Linux
sudo apk add --no-cache perl-rename
Command Syntax, Arguments, and Exit Status Codes
rename [options] 's/search/replacement/' files...
The syntax for the Perl-based rename utility is rename [options] 's/expression/replacement/[flags]' files.... The substitution expression mirrors Perl and sed regex syntax: s denotes substitution, expression defines the regex pattern to match, replacement is the new string to insert, and flags (such as g for global or i for case-insensitive) govern matching behavior. Always enclose the expression in single quotes to prevent the calling shell from interpreting special characters like $, *, or ().
The most important command flag is -n (or --no-act, dry run), which prints every file that would be renamed along with its target name without actually modifying anything on disk. Other essential options include -v (--verbose) to print changes as they are committed, and -f (--force) to overwrite existing destination files.
0— All specified files were processed and renamed successfully.1— Operational failure, such as file collision or permission denied on directory.2— Malformed regular expression or invalid command-line flag.130— Process interrupted by user signal (SIGINT, Ctrl+C).
Important Options and Flags Reference
| Option / Flag | Long Form / Argument | Technical Behavior and Purpose |
|---|---|---|
-n | --no-act | Dry-run mode: prints filenames that would be renamed without modifying files on disk. |
-v | --verbose | Verbose mode: displays the before-and-after name for each successfully renamed file. |
-f | --force | Forces overwrite of existing destination files without prompting. |
-e <expr> | --expr=<expr> | Specifies code expression to execute (can be specified multiple times). |
-d | --filename-only | Applies renaming expression only to the filename component, preserving directory paths. |
-s | --symlink | Renames symbolic link targets rather than the links themselves. |
-u | --unicode | Treats filenames as Unicode strings rather than raw byte sequences. |
-h | --help | Displays syntax help and summary of options. |
-V | --version | Displays the version of the rename implementation. |
Always run rename with the -n flag before committing changes. Reviewing the terminal output ensures that wildcards, capturing groups, and boundary anchors ($ and ^) behave as expected without causing unintended filename truncations.
Combining -v with -n gives a complete preview: rename -v -n 's/ /_/g' *.mp3 displays exactly which files contain spaces and what their new sanitized names will be.
When combining short flags on the command line, POSIX and GNU utilities allow clustering boolean flags behind a single hyphen, provided any option taking an argument appears last. In automated shell scripts, using long-form GNU options where portable makes self-documenting code that is easier to audit during peer review.
Practical Basic and Advanced Usage Examples
1. Preview Batch Filename Changes Safely with Dry-Run Mode
Test a regex renaming pattern across files without modifying any files on the filesystem.
rename -n 's/\.jpeg$/\.jpg/' *.jpeg
# Illustrative output (reviewed against documentation)
rename(photo1.jpeg, photo1.jpg)
rename(photo2.jpeg, photo2.jpg)
rename(vacation_2026.jpeg, vacation_2026.jpg)
The -n flag simulates execution, showing the exact source and target filenames so you can verify the regex before removing -n to apply changes.
2. Batch Change File Extensions Across Matching Files
Standardize HTML file extensions by changing .htm to .html across all files in the current folder.
rename -v 's/\.htm$/\.html/' *.htm
# Illustrative output (reviewed against documentation)
index.htm renamed as index.html
about.htm renamed as about.html
contact.htm renamed as contact.html
The regex matches .htm at the end of the filename ($) and replaces it with .html, while -v logs each successfully modified file.
3. Convert Filenames from Uppercase to Lowercase
Use the Perl transliteration operator (y///) to convert all uppercase letters to lowercase.
rename -v 'y/A-Z/a-z/' *
# Illustrative output (reviewed against documentation)
README.TXT renamed as readme.txt
DATA_REPORT.CSV renamed as data_report.csv
The y/A-Z/a-z/ operator functions like tr, mapping every uppercase character to its lowercase counterpart.
4. Replace Spaces in Filenames with Underscores
Sanitize filenames by replacing whitespace with underscores to make files shell- and web-safe.
rename -v 's/\s+/_/g' *
# Illustrative output (reviewed against documentation)
My Project Report 2026.pdf renamed as My_Project_Report_2026.pdf
Sales Summary Q1.xlsx renamed as Sales_Summary_Q1.xlsx
The \s+ regex matches one or more consecutive whitespace characters, and the trailing /g flag replaces all occurrences globally.
5. Add Date Prefixes to Filenames
Prepend a standard ISO date prefix to all CSV files in a data collection folder.
rename -v 's/^/2026-10-23-/' *.csv
# Illustrative output (reviewed against documentation)
export_users.csv renamed as 2026-10-23-export_users.csv
orders.csv renamed as 2026-10-23-orders.csv
The caret (^) matches the start of the filename string, allowing you to insert prefixes cleanly.
6. Strip Unwanted Substrings or Draft Tags
Remove '_draft' or temporary version tags from filenames before publishing.
rename -v 's/_draft//' *.docx
# Illustrative output (reviewed against documentation)
quarterly_review_draft.docx renamed as quarterly_review.docx
specification_v2_draft.docx renamed as specification_v2.docx
Matching '_draft' with an empty replacement string strips the token from matching filenames.
Real-World Workflows, Pipelines, and Shell Automation
Batch Media Asset Normalization Workflow for Web Deployments
A production script that sanitizes user-uploaded images: converting to lowercase, removing spaces, and standardizing extensions.
#!/usr/bin/env bash
set -euo pipefail
TARGET_DIR="/var/www/uploads"
cd "$TARGET_DIR"
echo "[ASSETS] Normalizing file names in $TARGET_DIR..."
# 1. Lowercase all files
rename 'y/A-Z/a-z/' *
# 2. Replace spaces and special characters with hyphens
rename 's/[^a-z0-9._-]/\-/g' *
# 3. Standardize extensions
rename 's/\.jpeg$/\.jpg/' *.jpeg 2>/dev/null || true
echo "[SUCCESS] Asset normalization complete."
# Illustrative output (reviewed against documentation)
[ASSETS] Normalizing file names in /var/www/uploads...
[SUCCESS] Asset normalization complete.
Chaining rename operations cleans up filenames to guarantee compatibility with web servers and CDNs without broken URL encodings.
Automated Log Rotation Archival Renaming Script
Rename daily rotated log files with padded timestamps before compressing and shipping to cloud storage.
#!/usr/bin/env bash
set -euo pipefail
DATE_TAG=$(date +%Y%m%d)
cd /var/log/custom-apps
echo "[LOGS] Tagging rotated logs with date $DATE_TAG..."
rename -v "s/\.log$/-${DATE_TAG}.log/" *.log
gzip -f *-"${DATE_TAG}".log
echo "[LOGS] Compressed and ready for S3 upload."
# Illustrative output (reviewed against documentation)
app.log renamed as app-20261023.log
worker.log renamed as worker-20261023.log
[LOGS] Compressed and ready for S3 upload.
Injecting shell variables into the rename regex allows dynamic date stamping before compression pipelines execute.
Pipelines, Redirection, Quoting, and Shell Expansion
When embedding rename inside shell pipelines (|), conditional chains (&& and ||), or command substitutions ($(...)), the calling shell performs tilde expansion, variable interpolation, and globbing before invoking the binary. Always wrap paths, patterns, and variables in quotes so whitespace and wildcard characters (*, ?) are not expanded prematurely, and use set -euo pipefail in unattended scripts.
Permissions, Security Implications, and Safe Execution
Bulk renaming files with incorrect regular expressions or the -f (force) option can overwrite existing files with identical names and corrupt application directory structures. Always test expressions first with the -n (dry run) flag before performing live batch renames.
Renaming a file requires write and execute permissions on the parent directory containing the file, rather than write permissions on the file itself. This is because renaming alters the directory's dentry mapping table, not the file's data blocks. In shared directories with the sticky bit (+t) enabled (such as /tmp), users can only rename files they own.
Because the Perl version of rename executes arbitrary Perl expressions, passing untrusted input or generating dynamic rename commands from user-supplied strings can introduce arbitrary code execution vulnerabilities. Ensure automated scripts sanitize input patterns or restrict expressions to simple literal substitutions.
GNU/Linux, BSD, and BusyBox Implementation Differences
A notorious point of confusion in the Linux world is that two completely different programs share the name 'rename'. Debian, Ubuntu, and Linux Mint ship the Perl script (File::Rename), which uses regex syntax 's/search/replace/'. In contrast, RHEL, CentOS, Rocky Linux, and Fedora historically ship the C program from util-linux, which uses simple string syntax: rename search replace files.
On Red Hat-based distributions, the Perl version is typically available in the EPEL repository as prename or perl-rename. For cross-distro shell scripts that must run reliably everywhere, writing a POSIX bash loop using parameter expansion (${f%.htm}.html) provides guaranteed portability without relying on either rename variant.
Troubleshooting Common Errors and Diagnostics
rename: syntax error or unrecognized option due to util-linux vs Perl rename
Root Cause: You are running on RHEL/CentOS/Fedora where /usr/bin/rename is the util-linux C binary, which does not accept Perl s/// regex syntax.
Resolution: Install the Perl version (prename or perl-rename), or use util-linux syntax: rename .htm .html *.htm.
# On RHEL / Fedora:
sudo dnf install -y prename
prename 's/\.htm$/\.html/' *.htm
Files not renamed because regex pattern does not match filenames
Root Cause: Special regex characters like dots (.) were not escaped, or shell wildcard expansion excluded hidden or differently formatted files.
Resolution: Escape literal dots as \. and verify matching patterns using rename -n.
rename -n 's/\.txt$/.bak/' *.txt
Target file already exists and overwrite was prevented
Root Cause: Renaming would result in a file collision with an existing file, and rename aborted to prevent data loss.
Resolution: Pass -f (--force) if overwriting is intended, or adjust the regex to create unique filenames.
rename -f 's/\.orig$//' *.orig
Alternatives, Related Commands, and Related Tutorials
- How to Rename a Directory in Linux: mv & rename Examples — Practical syntax, flags, and examples for
mv. - chown Command in Linux: Change File & Directory Ownership — Practical syntax, flags, and examples for
chown. - mkdir Command in Linux: Create Directories & Parent Trees — Practical syntax, flags, and examples for
mkdir. - How to Unzip Files in Linux: Extract, List & Exclude Guide — Practical syntax, flags, and examples for
unzip. - 25 Best Linux Commands Every Sysadmin Should Know — Core command-line utilities for daily Linux server administration.
- How to Find a File in Linux from the Command Line — Practical file search patterns across Linux directories.
- Linux Commands Knowledge Hub (#linux-commands) — Browse all Linux command-line tutorials and system administration references.
Authoritative References and Official Documentation

The Linux Command Line, 2nd Edition: A Complete Introduction
Frequently Asked Questions
Quick answers to common questions and configurations
Editorial Disclosure: Website Vidya is supported by our readers. When you purchase hosting, tools, or software through our verified partner links, we may earn an affiliate commission at no extra cost to you. We only recommend solutions we trust and rigorously verify.
Rajesh Ray
I’m Rajesh Rai, a full-stack developer, Linux administrator, and technology enthusiast passionate about making complex technology easier to understand and use.
Most Read Guides
TrendingUbuntu Server Not Booting? 10 Simple Steps to Fix It Fast
How to Create a 3D Button in HTML and CSS: Easy Steps
How to Install Python and Pip on Ubuntu 24.04 LTS
How to Install Nginx on Ubuntu 24.04
How to Install Python on Ubuntu 24.04 LTS
Related Technical Guides
Tested runbooks, server administration walkthroughs, and troubleshooting guides





Join the Conversation & Perspective
Have thoughts, counterpoints, or reflections on this story? Engage directly with fellow readers and editorial contributors.
No comments on this guide yet. Be the first to share your thoughts or ask a question!