BASH

Batch Rename Files Using Regular Expressions

Learn how to efficiently rename multiple files in a directory using Bash and regular expressions, ideal for organizing project assets or logs.

#!/bin/bash
# Navigate to the directory containing files to rename
# cd /path/to/your/files

# Example: Rename files from 'old-prefix-name.ext' to 'new-prefix-name.ext'
# Renames 'image-001.jpg' to 'photo-001.jpg'
# for file in old-prefix-*.ext; do
#     mv "$file" "$(echo "$file" | sed 's/^old-prefix-/new-prefix-/')"
# done

# More advanced example: Replace spaces with underscores and convert to lowercase
# Renames 'My Image 01.JPG' to 'my_image_01.jpg'
for file in *; do
    if [ -f "$file" ]; then
        # Replace spaces with underscores
        new_name=$(echo "$file" | tr ' ' '_')
        # Convert to lowercase
        new_name=$(echo "$new_name" | tr '[:upper:]' '[:lower:]')

        # Handle file extension conversion (optional, if you want to ensure .jpg)
        # new_name=$(echo "$new_name" | sed 's/\.jpeg$/.jpg/' | sed 's/\.png$/.jpg/')

        # Prevent renaming if the name hasn't changed or it's the script itself
        if [ "$file" != "$new_name" ] && [ "$new_name" != "$(basename "$0")" ]; then
            mv "$file" "$new_name"
            echo "Renamed '$file' to '$new_name'"
        fi
    fi
done

echo "Renaming complete."
How it works: This script iterates through all files in the current directory. For each file, it uses `tr` to replace spaces with underscores and convert all characters to lowercase. It then checks if the new name is different from the original and not the script itself before performing the `mv` command. This approach is highly flexible and can be adapted with different `sed` or `awk` commands for more complex renaming patterns.

Need help integrating this into your project?

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

Hire DigitalCodeLabs