Website Vidya
Cloud & DevOpsStep-by-Step Guide

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.

RR
Rajesh RayLead Systems Educator
Published:
10 min read
PDF Cheat Sheet
rename Command in Linux: Batch Rename Files with Regex
AI Executive SummaryWebsiteVidya AI

10 min read

Learn rename command in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.

Key Highlights
  • What rename Does and When to Use It
  • Availability and Installation Across Linux Distributions
  • Command Syntax, Arguments, and Exit Status Codes
Grounded in full engineering runbookWebsiteVidya AI Engine

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.

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.

Advertisement
rename Command in Linux: Batch Rename Files with Regex — syntax, flags, and practical terminal workflow diagram
rename Command in Linux: Batch Rename Files with Regex — command syntax, key options, and production workflow reference.

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:

Advertisement

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 / FlagLong Form / ArgumentTechnical Behavior and Purpose
-n--no-actDry-run mode: prints filenames that would be renamed without modifying files on disk.
-v--verboseVerbose mode: displays the before-and-after name for each successfully renamed file.
-f--forceForces overwrite of existing destination files without prompting.
-e <expr>--expr=<expr>Specifies code expression to execute (can be specified multiple times).
-d--filename-onlyApplies renaming expression only to the filename component, preserving directory paths.
-s--symlinkRenames symbolic link targets rather than the links themselves.
-u--unicodeTreats filenames as Unicode strings rather than raw byte sequences.
-h--helpDisplays syntax help and summary of options.
-V--versionDisplays 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.

Advertisement

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

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

Authoritative References and Official Documentation

Frequently Asked Questions

Quick answers to common questions and configurations

4 FAQs
Run rename --version or man rename. If the output mentions 'File::Rename' or Larry Wall, you have the Perl regex version. If it mentions 'util-linux' and authors like Andries Brouwer, you have the C string substitution version.
Append the global flag (/g) to the end of the substitution expression: rename 's/_/-/g' *.txt. Without the /g flag, only the first underscore in each filename is replaced.
By default, rename operates on the files passed to it. To rename recursively, combine rename with find: find . -type f -name '*.jpeg' -exec rename 's/\.jpeg$/\.jpg/' {} +.
The -d (or --filename-only) option applies the regular expression strictly to the base filename component and ignores leading directory paths. This prevents accidental modifications to parent directory names when passing paths like /path/to/my_file.txt.
RR
Written byVerified Author

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.

SPAM-FREE MODERATED DISCOURSE

Join the Conversation & Perspective

Have thoughts, counterpoints, or reflections on this story? Engage directly with fellow readers and editorial contributors.

AT
MP
JV
+2

No comments on this guide yet. Be the first to share your thoughts or ask a question!

Recommended Reading10 Guides

Related Technical Guides

Tested runbooks, server administration walkthroughs, and troubleshooting guides

Cloud & DevOps•

How to Close File Descriptors Above 9 in Dash Shell

Attempting to close a file descriptor above 9 in Dash using exec 10<&- results in a 10: not found error because Dash's POSIX lexer only recognizes single-digit file descriptors (0–9) in redirection operators. This guide explains the exact parser limitation, why FDs 10+ are reserved for internal shell state, and how to safely close inherited file descriptors using close_range, Python, or Perl wrappers.

RR
Rajesh Rai
Read More
Featured Infrastructure PartnerUp to 75% OFF + 3 Months Free

Supercharge Your Linux & Cloud Workloads with Hostinger

Deploy high-speed NVMe KVM VPS, Docker containers, and LiteSpeed-accelerated WordPress servers in under 60 seconds with full root access, dedicated IPv4, and 24/7 technical support.

Pure NVMe SSD StorageFull Root Access & SSHFree Domain & Unlimited SSL99.9% Uptime SLA
Plans from$2.99/mo
Claim Hostinger DealAffiliate link • Special discount applied at checkout