/ Bash Scripts

Batch file renaming with regex support

This guide provides instructions on how to create a Bash script for batch renaming files with regex support. The script will allow users to define their own custom options and settings.

Prerequisites

  • Familiarity with Bash scripting language
  • Understanding of regular expressions (regex)

Procedure

Step 1: Set Up the Script

Firstly, open your preferred text editor and create a new file. You can name the file whatever you prefer, but for the purpose of this guide, we’ll call it rename_files.sh.

At the top of this file, add the shebang line, which tells the system how to execute the file:

#!/bin/bash

Step 2: Add Argument Parsing

Next, you need to parse command-line arguments. We will be accepting three arguments: the source directory, the regex pattern to match, and the replacement string.

Here’s how to handle those arguments in the script:

# Check if the right number of arguments are passed
if [ $# -ne 3 ]; then
    echo "Usage: $0 <directory> <regex_pattern> <replacement>"
    exit 1
fi

# Assign arguments to variables
DIR=$1
REGEX=$2
REPLACEMENT=$3

Step 3: Validate Directory

We should check if the given directory exists and is readable before proceeding.

# Check if directory exists
if [ ! -d "$DIR" ]; then
    echo "Directory does not exist: $DIR"
    exit 1
fi

Step 4: Implement Regex Matching and File Renaming

Now, let’s iterate over the files in the given directory, match each file name against the provided regex, and rename the file if it matches:

# Use find to get all files in the directory
find "$DIR" -type f | while read -r file; do
    # Get the file name
    filename=$(basename -- "$file")

    # Check if the file name matches the regex
    if [[ $filename =~ $REGEX ]]; then
        # Rename the file
        new_filename="${filename//$REGEX/$REPLACEMENT}"
        mv -- "$file" "${file%/*}/$new_filename"
    fi
done

In this section, basename is used to extract the filename from the full path, and mv is used to rename the file. The // operator in ${filename//$REGEX/$REPLACEMENT} is a parameter expansion in bash which substitutes all occurrences of $REGEX with $REPLACEMENT in $filename.

Final Script

Combining all of the above, your final script should look like this:

#!/bin/bash

if [ $# -ne 3 ]; then
    echo "Usage: $0 <directory> <regex_pattern> <replacement>"
    exit 1
fi

DIR=$1
REGEX=$2
REPLACEMENT=$3

if [ ! -d "$DIR" ]; then
    echo "Directory does not exist: $DIR"
    exit 1
fi

find "$DIR" -type f | while read -r file; do
    filename=$(basename -- "$file")
    if [[ $filename =~ $REGEX ]]; then
        new_filename="${filename//$REGEX/$REPLACEMENT}"
        mv -- "$file" "${file%/*}/$new_filename"
    fi
done

Usage

Save the script, make it executable by running chmod +x rename_files.sh, and run it with your directory, regex pattern, and replacement as arguments:

./rename_files.sh /path/to/directory "regex_pattern" "replacement"

Conclusion

This script provides a simple way to batch rename files with regex support. It ensures that the provided directory exists and only attempts to rename files whose names match the provided regex pattern. Furthermore, it also implements basic error checking, making sure the correct number of arguments are provided when the script is run. Always remember to test your scripts on non-critical data to avoid losing any important files.

Was this helpful?

Thanks for your feedback!