Bash Script to Batch Rename Files Easily
Use a Bash loop like
for file in *.txt; do mv "$file" "newprefix_$file"; done to batch rename files by adding a prefix.Examples
InputFiles: report1.txt, report2.txt
OutputRenamed to: newprefix_report1.txt, newprefix_report2.txt
InputFiles: image1.jpg, image2.jpg
OutputRenamed to: photo_image1.jpg, photo_image2.jpg
InputFiles: fileA, fileB (no extension)
OutputRenamed to: renamed_fileA, renamed_fileB
How to Think About It
To batch rename files, think about looping over all files matching a pattern, then for each file, create a new name by adding or changing parts like prefixes or extensions, and finally rename the file using the
mv command.Algorithm
1
Get the list of files matching a pattern.2
For each file, create a new name by modifying the original name.3
Rename the file to the new name using the move command.4
Repeat until all files are processed.Code
bash
for file in *.txt; do newname="newprefix_$file" echo "Renaming '$file' to '$newname'" mv "$file" "$newname" done
Output
Renaming 'report1.txt' to 'newprefix_report1.txt'
Renaming 'report2.txt' to 'newprefix_report2.txt'
Dry Run
Let's trace renaming 'report1.txt' and 'report2.txt' by adding 'newprefix_'
1
List files
Files found: report1.txt, report2.txt
2
First file rename
Original: report1.txt, New: newprefix_report1.txt
3
Second file rename
Original: report2.txt, New: newprefix_report2.txt
| Original Filename | New Filename |
|---|---|
| report1.txt | newprefix_report1.txt |
| report2.txt | newprefix_report2.txt |
Why This Works
Step 1: Loop over files
The for loop goes through each file matching the pattern like *.txt.
Step 2: Create new name
We build a new filename by adding a prefix to the original filename.
Step 3: Rename file
The mv command renames the file from the old name to the new name.
Alternative Approaches
Using rename command
bash
rename 's/^/newprefix_/' *.txtThis is simpler but depends on the availability and version of the rename tool on your system.
Using find with exec
bash
find . -maxdepth 1 -name '*.txt' -exec bash -c 'mv "$0" "newprefix_$0"' {} \;
Useful for more complex directory structures but more complex syntax.
Complexity: O(n) time, O(1) space
Time Complexity
The script processes each file once in a loop, so time grows linearly with the number of files.
Space Complexity
The script uses constant extra space, renaming files in place without storing large data.
Which Approach is Fastest?
The simple Bash loop and the rename command both run in O(n) time; rename is often faster but less flexible.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Bash loop with mv | O(n) | O(1) | Simple, flexible renaming |
| rename command | O(n) | O(1) | Quick renaming with regex |
| find with exec | O(n) | O(1) | Complex directory structures |
Always test your batch rename script with
echo before running mv to avoid mistakes.Forgetting to quote filenames with spaces, causing errors or unexpected behavior.