BASH
Batch Rename Multiple Files Using Regular Expressions
Efficiently rename a collection of files in a directory by applying a regular expression search and replace pattern, ideal for organizing assets or refactoring filenames.
#!/bin/bash
# Usage: ./batch_rename.sh "search_regex" "replace_string"
# Example: ./batch_rename.sh "image-" "photo_"
# This will rename "image-01.jpg" to "photo_01.jpg"
SEARCH_PATTERN="$1"
REPLACE_STRING="$2"
if [ -z "$SEARCH_PATTERN" ] || [ -z "$REPLACE_STRING" ]; then
echo "Usage: $0 <search_regex> <replace_string>"
echo "Example: $0 \"^prefix_\" \"new_prefix-\""
exit 1
fi
echo "Batch renaming files with pattern '$SEARCH_PATTERN' to '$REPLACE_STRING'..."
for filename in *; do
if [ -f "$filename" ]; then # Only process files
new_filename=$(echo "$filename" | sed "s/$SEARCH_PATTERN/$REPLACE_STRING/")
if [ "$filename" != "$new_filename" ]; then
echo "Renaming '$filename' to '$new_filename'"
mv "$filename" "$new_filename"
fi
fi
done
echo "Batch rename complete."
How it works: This script provides a powerful way to batch rename files in the current directory using regular expressions. It iterates through all files, applies a `sed` command to perform a search and replace operation on each filename, and then renames the file if a change occurred. This is invaluable for organizing web assets, refactoring naming conventions, or preparing files for deployment.