BASH

Batch Rename Files with a Pattern

Efficiently rename multiple files based on a pattern using a Bash script, useful for organizing assets or cleaning up project directories in web development workflows.

#!/bin/bash

# Define the directory to process (current directory if not specified)
TARGET_DIR="."

# Check if a directory was provided as an argument
if [ -n "$1" ]; then
    TARGET_DIR="$1"
    if [ ! -d "$TARGET_DIR" ]; then
        echo "Error: Directory '$TARGET_DIR' not found."
        exit 1
    fi
fi

echo "Processing files in: $(readlink -f "$TARGET_DIR")"

# Example: Rename files from "image-1.jpg" to "product-photo-1.jpg"
# Or: Rename files removing spaces "my file.txt" to "my_file.txt"

# Option 1: Rename by adding a prefix
# for FILE in "${TARGET_DIR}"/*.jpg; do
#     if [ -f "$FILE" ]; then
#         BASENAME=$(basename "$FILE")
#         DIRNAME=$(dirname "$FILE")
#         NEW_NAME="${DIRNAME}/product-photo-${BASENAME}"
#         echo "Renaming '$FILE' to '$NEW_NAME'"
#         # mv -n "$FILE" "$NEW_NAME" # Use -n to prevent overwriting
#     fi
# done

# Option 2: Replace spaces with underscores
for FILE in "${TARGET_DIR}"/*\ *; do # Matches files with spaces in their names
    if [ -f "$FILE" ]; then
        NEW_NAME=$(echo "$FILE" | tr ' ' '_')
        if [ "$FILE" != "$NEW_NAME" ]; then
            echo "Renaming '$FILE' to '$NEW_NAME'"
            mv -n "$FILE" "$NEW_NAME" # Use -n to prevent overwriting
        fi
    fi
done

# Option 3: Replace a specific string pattern
# SOURCE_PATTERN="old_prefix_"
# TARGET_PATTERN="new_prefix_"
# for FILE in "${TARGET_DIR}"/${SOURCE_PATTERN}*; do
#     if [ -f "$FILE" ]; then
#         BASENAME=$(basename "$FILE")
#         DIRNAME=$(dirname "$FILE")
#         NEW_BASENAME=$(echo "$BASENAME" | sed "s/${SOURCE_PATTERN}/${TARGET_PATTERN}/")
#         NEW_NAME="${DIRNAME}/${NEW_BASENAME}"
#         if [ "$FILE" != "$NEW_NAME" ]; then
#             echo "Renaming '$FILE' to '$NEW_NAME'"
#             # mv -n "$FILE" "$NEW_NAME"
#         fi
#     fi
# done

echo "Batch renaming complete."
echo "Note: The actual 'mv' commands are commented out in the example. Uncomment to execute."
How it works: This Bash script provides a flexible way to batch rename multiple files within a specified directory. It iterates through files matching certain patterns and applies renaming logic. The example specifically demonstrates how to replace spaces in filenames with underscores using `tr`, which is a common task for standardizing filenames, especially for web assets or uploaded content. Other commented-out examples show how to add prefixes or replace specific string patterns using `sed`. The actual `mv` commands are commented out by default to allow for safe testing before execution.

Need help integrating this into your project?

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

Hire DigitalCodeLabs