BASH
Batch Rename Files with a Pattern or String Replacement
Automate renaming multiple files in a directory using a specified pattern or string replacement, perfect for organizing web assets.
#!/bin/bash
# Configuration
SEARCH_STRING="old_prefix_"
REPLACE_STRING="new_prefix_"
TARGET_DIR="./assets"
# Ensure the target directory exists
if [ ! -d "$TARGET_DIR" ]; then
echo "Error: Target directory '$TARGET_DIR' does not exist." >&2
exit 1
fi
echo "Scanning '$TARGET_DIR' for files to rename..."
COUNT=0
# Loop through all files in the target directory
# Adjust '*.jpg' or '*' to match specific file types or all files
for filepath in "$TARGET_DIR"/*;
do
# Check if it's a regular file and not a directory
if [ -f "$filepath" ]; then
filename=$(basename "$filepath")
# Check if the filename contains the SEARCH_STRING
if [[ "$filename" == *"$SEARCH_STRING"* ]]; then
# Perform string replacement
new_filename=$(echo "$filename" | sed "s/${SEARCH_STRING}/${REPLACE_STRING}/g")
new_filepath="$TARGET_DIR/$new_filename"
if [ "$filename" != "$new_filename" ]; then
echo "Renaming: '$filename' to '$new_filename'"
mv "$filepath" "$new_filepath" || {
echo "Error: Failed to rename '$filename'." >&2
}
((COUNT++))
fi
fi
fi
done
echo "
Finished renaming. Total files renamed: $COUNT."
How it works: This script provides a convenient way to batch rename files within a specified directory based on a search and replace pattern. It iterates through all files, checks if they are regular files (not directories), and then uses `sed` for string replacement within the filename. The `mv` command performs the actual rename. This is particularly useful for web developers managing asset libraries, where consistent naming conventions are crucial, allowing for quick adjustments across many files.