BASH
Batch Rename Multiple Files with a Specific Pattern
Learn to use a Bash script to efficiently rename multiple files in a directory by applying a common prefix, suffix, or replacing parts of their names.
#!/bin/bash
# Configuration
TARGET_DIR="./images" # Directory containing files to rename
OLD_PATTERN="image_" # Part of the filename to replace
NEW_PATTERN="photo_" # Replacement part
FILE_EXTENSION="jpg" # Process only files with this extension (e.g., "png", "txt", "*")
DRY_RUN=true # Set to 'false' to actually rename files. If 'true', it only prints what it *would* do.
# --- Functions ---
log_message() {
echo "[$(date +'%Y-%m-%d %H:%M:%S')] $1"
}
# --- Main Script ---
log_message "Starting batch rename operation in $TARGET_DIR..."
if [ ! -d "$TARGET_DIR" ]; then
log_message "ERROR: Target directory $TARGET_DIR does not exist."
exit 1
fi
if [ "$DRY_RUN" = true ]; then
log_message "DRY RUN MODE: No files will actually be renamed. Printing proposed changes."
else
log_message "LIVE RUN MODE: Files will be renamed."
fi
COUNTER=0
# Loop through files matching the extension
# Using 'find' with '-depth' for safety if renaming directories too, but here focused on files
find "$TARGET_DIR" -maxdepth 1 -type f -name "*.${FILE_EXTENSION}" | while read -r old_path; do
filename=$(basename "$old_path")
dirname=$(dirname "$old_path")
# Replace OLD_PATTERN with NEW_PATTERN in the filename
new_filename="${filename/$OLD_PATTERN/$NEW_PATTERN}"
new_path="$dirname/$new_filename"
if [ "$filename" != "$new_filename" ]; then
log_message "Proposed: '$filename' -> '$new_filename'"
if [ "$DRY_RUN" = false ]; then
mv "$old_path" "$new_path"
if [ $? -eq 0 ]; then
log_message "Renamed: '$old_path' to '$new_path'"
COUNTER=$((COUNTER + 1))
else
log_message "ERROR: Failed to rename '$old_path'."
fi
fi
fi
done
if [ "$DRY_RUN" = false ]; then
log_message "Renamed $COUNTER files."
fi
log_message "Batch rename operation finished."
How it works: This script provides a flexible way to batch rename files within a specified directory. It iterates through files matching a given extension, replaces a defined `OLD_PATTERN` in their names with a `NEW_PATTERN`, and performs the renaming. A `DRY_RUN` option allows previewing changes before actual execution, making it safe for managing image assets or other structured files.