Renaming File Methods
Basic Renaming Commands
1. mv Command
The most common method for renaming files in Linux is the mv
command.
## Basic syntax
mv original_name.txt new_name.txt
## Renaming a single file
mv report.txt annual_report.txt
## Renaming multiple files
mv document1.txt document_updated.txt
2. Rename Utility
A powerful tool for batch renaming files with more complex patterns.
## Install rename utility
sudo apt-get install rename
## Basic rename syntax
rename 's/old_pattern/new_pattern/' files
## Example: Changing file extension
rename 's/\.txt$/\.log/' *.txt
Advanced Renaming Techniques
graph TD
A[Renaming Methods] --> B[Single File Rename]
A --> C[Batch Renaming]
A --> D[Scripted Renaming]
B --> E[mv Command]
C --> F[rename Utility]
D --> G[Shell Scripting]
Batch Renaming Scenarios
Scenario |
Command |
Example |
Change Extension |
rename 's/.old$/.new/' * |
Rename *.old to *.new |
Lowercase Conversion |
rename 'y/A-Z/a-z/' * |
Convert filenames to lowercase |
Remove Spaces |
rename 's/ /_/g' * |
Replace spaces with underscores |
Safe Renaming Practices
Shell Script for Safe Renaming
#!/bin/bash
## Safe renaming script
## Check if file exists
if [ -f "$1" ]; then
## Create backup before renaming
cp "$1" "$1.bak"
## Rename file
mv "$1" "$2"
echo "File renamed safely"
else
echo "Error: File does not exist"
fi
LabEx Tip
In LabEx Linux environments, always use careful renaming methods to prevent data loss and maintain file integrity.
Error Prevention
- Always backup files before renaming
- Use quotes with filenames containing spaces
- Verify file existence before renaming
- Use wildcards cautiously
Common Renaming Challenges
Handling Special Characters
## Renaming files with special characters
mv "file with spaces.txt" renamed_file.txt
## Using find for complex renaming
find . -type f -name "*.TXT" -exec rename 's/\.TXT$/.txt/' {} \;