How to Rename Files in Linux: Complete Guide to mv, rename, find, and Bash Scripts
Renaming files in Linux is one of the most frequent administrative tasks you'll encounter — whether you're managing a single server, maintaining a large web hosting environment, or automating deployment pipelines. Linux offers multiple approaches to file renaming, from the straightforward mv command to powerful batch-renaming utilities and custom Bash scripts. This comprehensive guide covers every method you need, with practical examples you can apply immediately.
Why File Renaming Matters in Linux Administration
On any Linux-based system — including VPS Hosting environments, dedicated servers, or shared hosting accounts — proper file organization directly impacts system performance, security, and maintainability. Misconfigured filenames can break web applications, disrupt cron jobs, and create permission issues. Knowing how to rename files efficiently and safely is a fundamental skill for any systems administrator or developer.
Method 1: Renaming Files with the mv Command
The mv (move) command is the most basic and universally available tool for renaming files in Linux. Although its primary purpose is moving files and directories between locations, it doubles as a highly effective renaming tool.
Basic Syntax
mv old_filename new_filenameSimple File Rename Example
To rename file1.txt to file2.txt within the same directory:
mv file1.txt file2.txtThis command renames the file in place — no copy is created, and no additional disk space is consumed. The operation is atomic on most Linux filesystems, making it safe even in production environments.
Renaming Files Across Directories
You can simultaneously rename and relocate a file:
mv /var/www/html/old_config.php /var/www/html/config.phpUseful mv Flags
| Flag | Description |
|---|---|
-i | Prompts before overwriting an existing file |
-n | Never overwrites an existing file |
-v | Verbose output — shows what was renamed |
-b | Creates a backup of the destination file if it exists |
Example with interactive prompt:
mv -i old_filename.txt new_filename.txtExample with verbose output:
mv -v report_draft.txt report_final.txt
# Output: 'report_draft.txt' -> 'report_final.txt'Limitations of mv for Batch Renaming
While mv is excellent for renaming individual files, renaming dozens or hundreds of files one at a time becomes impractical. For batch operations, more advanced tools are required.
Method 2: Batch Renaming Files with the rename Command
The rename command is a powerful Perl-based utility designed specifically for renaming multiple files simultaneously using regular expressions. It dramatically reduces the time needed for complex, pattern-based renaming tasks.
Installing rename
Depending on your Linux distribution, rename may not be pre-installed.
Debian/Ubuntu:
sudo apt install renameCentOS/RHEL/AlmaLinux:
sudo yum install prenameVerify installation:
rename --versionBasic Syntax
rename 's/old_pattern/new_pattern/' filesThis uses Perl-compatible regular expression (PCRE) syntax, giving you enormous flexibility.
Example 1: Change File Extensions
Rename all .txt files to .md:
rename 's/.txt$/.md/' *.txtBreakdown:
s/ — substitution command
.txt$ — matches .txt at the end of the filename
.md — replaces it with .md*.txt — applies to all .txt files in the current directory
Example 2: Add a Prefix to Multiple Files
Add the prefix new_ to all .txt files:
rename 's/^/new_/' *.txt
This turns report.txt into new_report.txt, notes.txt into new_notes.txt, and so on.
Example 3: Add a Suffix Before the File Extension
Add _backup before the .txt extension:
rename 's/.txt$/_backup.txt/' *.txt
This converts config.txt to config_backup.txt.
Example 4: Convert Filenames to Lowercase
rename 's/[A-Z]/lc($&)/ge' *.txt
This is particularly useful when migrating files from Windows systems, where filenames are case-insensitive, to Linux servers where case sensitivity can cause application errors.
Example 5: Replace Spaces with Underscores
rename 's/ /_/g' *
Spaces in filenames can cause issues in shell scripts and web server configurations — this command eliminates them across all files in the current directory.
Dry Run (Preview Changes Without Executing)
Always use the -n flag to preview what rename will do before committing:
rename -n 's/.txt$/.md/' *.txt
This prints the planned renames without actually performing them — an essential safety practice in production environments.
Method 3: Renaming Files Using find Combined with mv
When you need to rename files across multiple directories or based on complex criteria — such as file age, size, or ownership — combining find with mv provides the most flexible solution.
Basic Syntax
find /path -name "pattern" -exec bash -c 'mv "$1" "new_name"' -- {} ;
Example 1: Rename All .log Files to .txt Recursively
find . -name "*.log" -exec bash -c 'mv "$1" "${1%.log}.txt"' -- {} ;
Breakdown:
find . -name "*.log" — finds all .log files starting from the current directory, recursively
-exec bash -c '...' -- {} ; — executes a shell command for each found file
"${1%.log}.txt" — uses parameter expansion to strip .log and append .txtExample 2: Rename Files Modified in the Last 7 Days
find /var/log -name "*.log" -mtime -7 -exec bash -c 'mv "$1" "${1%.log}_archive.log"' -- {} ;This is useful for log rotation and archiving workflows on servers.
Example 3: Rename Files Owned by a Specific User
find /home -user john -name "*.conf" -exec bash -c 'mv "$1" "${1%.conf}.conf.bak"' -- {} ;Performance Tip: Use + Instead of ;
When renaming large numbers of files, using + at the end of -exec is more efficient because it batches commands:
find . -name "*.tmp" -exec bash -c 'for f; do mv "$f" "${f%.tmp}.bak"; done' _ {} +Method 4: Renaming Files Using a Bash Script
For repetitive or large-scale renaming tasks — such as nightly batch jobs on a Dedicated Server — a custom Bash script provides the most control, repeatability, and auditability.
Step-by-Step: Creating a File Renaming Bash Script
#### Step 1: Create the Script File
Use a text editor to create your script:
nano rename_script.sh#### Step 2: Write the Script
#!/bin/bash
# Script: rename_script.sh
# Purpose: Rename all .txt files in the current directory to .md
# Usage: ./rename_script.sh
echo "Starting file rename operation..."
for file in *.txt; do
# Check if any .txt files exist
if [ ! -e "$file" ]; then
echo "No .txt files found in the current directory."
exit 1
fi
new_name="${file%.txt}.md"
mv -v "$file" "$new_name"
echo "Renamed: $file -> $new_name"
done
echo "Rename operation complete."#### Step 3: Make the Script Executable
chmod +x rename_script.sh#### Step 4: Run the Script
./rename_script.sh#### Step 5: Verify the Changes
ls -laAdvanced Bash Script: Rename with Logging and Error Handling
For production server environments, always include logging and error handling:
#!/bin/bash
LOG_FILE="/var/log/rename_operations.log"
TIMESTAMP=$(date '+%Y-%m-%d %H:%M:%S')
TARGET_DIR="${1:-.}"
OLD_EXT="${2:-txt}"
NEW_EXT="${3:-md}"
echo "[$TIMESTAMP] Starting rename: .$OLD_EXT -> .$NEW_EXT in $TARGET_DIR" >> "$LOG_FILE"
count=0
errors=0
for file in "$TARGET_DIR"/*."$OLD_EXT"; do
if [ -f "$file" ]; then
new_name="${file%.$OLD_EXT}.$NEW_EXT"
if mv -v "$file" "$new_name" >> "$LOG_FILE" 2>&1; then
((count++))
else
echo "[$TIMESTAMP] ERROR: Failed to rename $file" >> "$LOG_FILE"
((errors++))
fi
fi
done
echo "[$TIMESTAMP] Done. Renamed: $count files. Errors: $errors" >> "$LOG_FILE"
echo "Renamed $count files with $errors errors. See $LOG_FILE for details."Usage:
./rename_script.sh /var/www/html txt mdThis script accepts the target directory, old extension, and new extension as arguments — making it fully reusable across different projects and environments.
Method 5: Renaming Files Using a Graphical File Manager (GUI)
For users who prefer a visual interface — particularly on desktop Linux distributions — most graphical file managers include built-in rename functionality.
Common Linux File Managers
| File Manager | Desktop Environment | Bulk Rename Support |
|---|---|---|
| Nautilus | GNOME | Via right-click or plugins |
| Dolphin | KDE Plasma | Built-in batch rename tool |
| Thunar | XFCE | Built-in bulk rename utility |
| Nemo | Cinnamon | Via right-click |
How to Rename a File in a GUI File Manager
- Open your file manager (Nautilus, Dolphin, Thunar, etc.)
- Navigate to the directory containing the file
- Right-click the file and select Rename
- Type the new filename
- Press Enter to confirm
Bulk Rename in Thunar
Thunar includes a particularly powerful bulk rename tool:
- Select multiple files
- Go to Edit → Rename
- Choose a renaming pattern (insert date, number sequence, search and replace, etc.)
- Preview changes and click Rename
This is ideal for photographers, content creators, and developers working on local Linux workstations.
Comparing All File Renaming Methods
| Method | Best For | Batch Support | Regex Support | Requires Installation |
|---|---|---|---|---|
mv | Single file renames | No | No | No (built-in) |
rename | Pattern-based batch renaming | Yes | Yes (Perl) | Sometimes |
find + mv | Multi-directory, criteria-based | Yes | Partial | No (built-in) |
| Bash script | Automated, repetitive tasks | Yes | Yes | No |
| GUI file manager | Visual, interactive renaming | Limited | No | Depends on DE |
Best Practices for Safe File Renaming on Linux Servers
Whether you're managing files on a VPS with cPanel or a bare-metal dedicated server, follow these best practices to avoid costly mistakes:
- Always preview before executing — Use
rename -norecho mvto dry-run your commands - Back up important files — Before bulk renaming, create a backup:
cp -r /target/dir /backup/dir - Test on a small subset first — Apply your rename command to a single file or small group before running it on thousands of files
- Use version control — If renaming source code files, commit your current state to Git before proceeding
- Check for dependent processes — Renaming configuration files, log files, or web assets may break running applications; always check dependencies first
- Avoid special characters — Filenames with spaces,
&,*,?, or!can cause unexpected behavior in shell commands; sanitize filenames when possible - Log all operations — On production servers, always log rename operations for auditing and rollback purposes
Common Use Cases in Web Hosting and Server Administration
File renaming is not just a housekeeping task — it has direct implications for web hosting operations. Here are real-world scenarios where efficient file renaming is critical:
- Migrating a website — Renaming PHP files, configuration files, or asset directories when moving between hosting providers
- SSL certificate management — Renaming certificate files to match expected naming conventions when deploying SSL Certificates on your server
- Deploying email configurations — Renaming template files and configuration files when setting up Email Hosting services
- Log rotation — Automatically renaming and archiving log files on a schedule using Bash scripts and cron jobs
- Domain migrations — Renaming document root directories and virtual host configuration files when managing Domain Registration and DNS changes
Conclusion
Linux provides a rich set of tools for renaming files, each suited to different scenarios and skill levels:
mvis your go-to for quick, single-file renames with no additional dependenciesrenameexcels at pattern-based batch renaming using powerful Perl regular expressionsfind+mvoffers the greatest flexibility for multi-directory and criteria-based renaming- Bash scripts provide automation, repeatability, and error handling for production environments
- GUI file managers offer an accessible, visual approach for desktop users
Mastering these techniques will make you a more effective Linux administrator, whether you're managing a personal project or maintaining enterprise-level infrastructure. The key is choosing the right tool for the task at hand — and always testing before executing in a live environment.
*Looking for a reliable Linux hosting environment to practice and deploy your projects? Explore AlexHost's VPS Hosting plans for full root access, SSD storage, and 24/7 technical support — everything you need to run Linux workloads with confidence.*
