Bash Script to Rename Multiple Files Easily
for file in *.txt; do mv "$file" "new_$file"; done to rename multiple files by adding a prefix or changing names.Examples
How to Think About It
mv command. This way, you automate renaming many files quickly.Algorithm
Code
for file in *.txt; do new_name="new_$file" echo "Renaming $file to $new_name" mv "$file" "$new_name" done
Dry Run
Let's trace renaming report1.txt and report2.txt by adding 'new_' prefix.
List files
Files found: report1.txt, report2.txt
Rename first file
file=report1.txt, new_name=new_report1.txt, command: mv "report1.txt" "new_report1.txt"
Rename second file
file=report2.txt, new_name=new_report2.txt, command: mv "report2.txt" "new_report2.txt"
| File | New Name | Command |
|---|---|---|
| report1.txt | new_report1.txt | mv "report1.txt" "new_report1.txt" |
| report2.txt | new_report2.txt | mv "report2.txt" "new_report2.txt" |
Why This Works
Step 1: Loop over files
The for loop picks each file matching the pattern one by one.
Step 2: Create new name
We build the new file name by adding a prefix like new_ before the original name.
Step 3: Rename file
The mv command renames the file from the old name to the new name.
Alternative Approaches
rename 's/^/new_/' *.txtfind . -maxdepth 1 -name '*.txt' -exec bash -c 'mv "$0" "new_$0"' {} \;
count=1 for file in *.txt; do mv "$file" "file_$count.txt" ((count++)) done
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, only storing temporary variables for each file.
Which Approach is Fastest?
Using the rename command is fastest for simple patterns, but loops offer more flexibility.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Bash loop with mv | O(n) | O(1) | Flexible renaming rules |
| rename command | O(n) | O(1) | Simple pattern renaming, faster |
| find with exec | O(n) | O(1) | Complex file selection |
echo before running mv to avoid mistakes.