BASH

Batch Rename Files with a Prefix/Suffix

Easily rename multiple files in a directory by adding a common prefix or suffix. This bash snippet uses a loop and `mv` to apply a consistent naming convention across many files.

#!/bin/bash

# Configuration
TARGET_DIR="./my_files" # Directory containing files to rename
PREFIX="new_" # Prefix to add, e.g., "backup_" or "data_"
# SUFFIX="_old" # Uncomment and use if you want to add a suffix instead

# Create some dummy files for demonstration (optional)
mkdir -p "$TARGET_DIR"
touch "$TARGET_DIR"/document_1.txt
touch "$TARGET_DIR"/image_abc.jpg
touch "$TARGET_DIR"/report.pdf

echo "Original files in '$TARGET_DIR':"
ls "$TARGET_DIR"

echo "Renaming files in '$TARGET_DIR' by adding prefix '$PREFIX'..."

# Iterate over each item in the target directory
for file in "$TARGET_DIR"/*; do
  # Check if the current item is a regular file
  if [ -f "$file" ]; then
    filename=$(basename "$file") # Extract just the filename
    dirname=$(dirname "$file")   # Extract the directory path
    
    # Construct the new filename with the prefix
    new_filename="$PREFIX$filename"
    # If adding a suffix:
    # base=${filename%.*}
    # ext=${filename##*.}
    # new_filename="${base}${SUFFIX}.${ext}"
    
    # Rename the file using mv
    mv "$file" "$dirname/$new_filename"
    echo "Renamed '$filename' to '$new_filename'"
  fi
done

echo "Files after renaming:"
ls "$TARGET_DIR"
How it works: This script provides a powerful way to perform bulk renaming of files within a specified directory. It iterates through each file, extracts its base name and directory path using `basename` and `dirname`, and then constructs a new filename by prepending a defined `PREFIX`. The `mv` command is then used to execute the rename operation. This snippet is highly useful for organizing files, standardizing naming conventions, or preparing files for processing by other scripts or applications.

Need help integrating this into your project?

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

Hire DigitalCodeLabs