BASH

Batch Renaming Files with Prefixes or Suffixes

Efficiently rename multiple files in a directory by adding custom prefixes or suffixes, useful for organizing assets, images, or managing build outputs.

#!/bin/bash

# Usage: ./rename_files.sh <directory> <prefix/suffix_type> <string>
# Example: ./rename_files.sh . prefix new_ 
# Example: ./rename_files.sh images suffix _old

DIR="${1:-.}" # Default to current directory if not provided
TYPE="$2"
STR="$3"

if [ -z "$TYPE" ] || [ -z "$STR" ]; then
  echo "Usage: $0 <directory> <prefix|suffix> <string>"
  exit 1
fi

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

echo "Renaming files in directory: $DIR"

case "$TYPE" in
  prefix)
    for file in "$DIR"/*; do
      if [ -f "$file" ]; then
        FILENAME=$(basename "$file")
        DIRNAME=$(dirname "$file")
        NEW_FILENAME="${STR}${FILENAME}"
        echo "Renaming '$FILENAME' to '$NEW_FILENAME'"
        mv "$file" "$DIRNAME/$NEW_FILENAME"
      fi
    done
    ;;
  suffix)
    for file in "$DIR"/*; do
      if [ -f "$file" ]; then
        FILENAME=$(basename "$file")
        DIRNAME=$(dirname "$file")
        EXTENSION="${FILENAME##*.}" # Get file extension
        NAME_WITHOUT_EXT="${FILENAME%.*}" # Get filename without extension

        if [ "$FILENAME" = "$EXTENSION" ]; then # No extension found
          NEW_FILENAME="${FILENAME}${STR}"
        else
          NEW_FILENAME="${NAME_WITHOUT_EXT}${STR}.${EXTENSION}"
        fi
        
        echo "Renaming '$FILENAME' to '$NEW_FILENAME'"
        mv "$file" "$DIRNAME/$NEW_FILENAME"
      fi
    done
    ;;
  *)
    echo "Invalid type. Please use 'prefix' or 'suffix'." >&2
    exit 1
    ;;
esac

echo "Batch renaming complete."
How it works: This script provides a flexible way to batch rename files by adding a specified string as either a prefix or a suffix. It takes the directory, type ('prefix' or 'suffix'), and the string to add as arguments. It iterates through all files in the target directory, constructs the new filename based on the chosen type, and uses the `mv` command to rename them. The suffix logic is smart enough to place the suffix before the file extension if one exists, making it ideal for managing web assets like images or compiled scripts.

Need help integrating this into your project?

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

Hire DigitalCodeLabs