BASH

Batch Rename Files in a Directory

Learn to efficiently rename multiple files in a directory using a Bash `for` loop, enabling consistent naming conventions or bulk adjustments for web assets.

#!/bin/bash

# Configuration variables
TARGET_DIR="."     # Directory to process (current directory by default)
OLD_EXTENSION="txt" # The original file extension
NEW_EXTENSION="md"  # The new file extension

# Change to the target directory
cd "$TARGET_DIR" || { echo "Error: Directory '$TARGET_DIR' not found." >&2; exit 1; }

# Loop through all files with the old extension
for file in *."$OLD_EXTENSION"; do
  # Check if the file actually exists (prevents error if no files match)
  if [ -f "$file" ]; then
    # Construct the new filename using parameter expansion
    new_file="${file%.$OLD_EXTENSION}.$NEW_EXTENSION"
    
    # Perform the rename
    mv -- "$file" "$new_file"
    echo "Renamed '$file' to '$new_file'"
  fi
done

echo "Batch renaming complete."
How it works: This script demonstrates how to batch rename files within a specified directory using a `for` loop. It iterates through all files matching a `*.$OLD_EXTENSION` pattern. The `if [ -f "$file" ]` check prevents errors if no files with the specified extension are found. The core of the renaming is `mv -- "$file" "${file%.$OLD_EXTENSION}.$NEW_EXTENSION"`. The parameter expansion `${file%.$OLD_EXTENSION}` removes the original extension from the filename, allowing you to easily append the `NEW_EXTENSION`. This is invaluable for organizing assets or changing file types.

Need help integrating this into your project?

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

Hire DigitalCodeLabs