« Back to Index

Shell: rename files matching specific pattern

View original Gist on GitHub

Tags: #shell #bash #macos #files #rename

filerename.sh

#!/bin/bash

# Iterate over each MP4 file in the current directory
for file in *.mp4; do
  # Check if the file matches the pattern: MMDDYYYY <NAME>.mp4
  if [[ "$file" =~ ^([0-9]{2})([0-9]{2})([0-9]{4})\ (.*)\.mp4$ ]]; then
    # Extract the parts of the filename
    MM="${BASH_REMATCH[1]}"
    DD="${BASH_REMATCH[2]}"
    YYYY="${BASH_REMATCH[3]}"

    # Construct the new filename (YYYY.MM.DD.mp4)
    new_filename="${YYYY}.${MM}.${DD}.mp4"

    # Rename the file
    mv "$file" "$new_filename"

    # Print a message indicating the rename
    echo "Renamed '$file' to '$new_filename'"
  else
    echo "File '$file' does not match the expected pattern."
  fi
done