← Back to all snippets
BASH

Batch Rename Files with a Specific Pattern

Automate the renaming of multiple files in a directory using Bash. This script allows you to add prefixes, suffixes, or replace substrings in filenames.

#!/bin/bash

# Usage: rename_files.sh <directory> <search_pattern> <replace_pattern>
# Example: rename_files.sh ./images "old_" "new_prefix_"
# Example: rename_files.sh .png .jpg (to change extension)

if [ "$#" -ne 3 ]; then
    echo "Usage: $0 <directory> <search_pattern> <replace_pattern>"
    echo "Example: $0 ./assets/images "IMG_" "thumb_" (adds thumb_ to files starting with IMG_)"
    echo "Example: $0 ./docs .md .txt (changes .md extension to .txt)"
    exit 1
fi

TARGET_DIR="$1"
SEARCH_PATTERN="$2"
REPLACE_PATTERN="$3"

if [ ! -d "$TARGET_DIR" ]; then
    echo "Error: Directory '$TARGET_DIR' not found."
    exit 1
fi

# Change to the target directory
cd "$TARGET_DIR" || { echo "Error: Could not change to directory '$TARGET_DIR'"; exit 1; }

# Find files and loop through them
for file in *"$SEARCH_PATTERN"*; do
    # Skip if it's a directory or if the file doesn't exist (e.g., if no match for pattern)
    [ -f "$file" ] || continue

    NEW_NAME=$(echo "$file" | sed "s/${SEARCH_PATTERN}/${REPLACE_PATTERN}/g")

    if [ "$file" != "$NEW_NAME" ]; then
        echo "Renaming '$file' to '$NEW_NAME'"
        mv "$file" "$NEW_NAME"
    else
        echo "Skipping '$file' (no change)"
    fi
done

echo "Batch rename complete in $TARGET_DIR."
How it works: This script helps web developers automate the tedious task of renaming multiple files in a directory. It takes a target directory, a search pattern, and a replacement pattern. It then iterates through all files in the specified directory, and for each file whose name contains the search pattern, it generates a new name by replacing the pattern. This is particularly useful for organizing static assets, optimizing image names, or standardizing file conventions across a project.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs