#!/bin/bash # Credit: # Mitsuo, GPT4 # 2023年 11月 8日 水曜日 15:46:55 -05 # Check for proper number of command line args. expected_args=3 if [ $# -ne $expected_args ]; then echo "Usage: $1 {prefix} {date in yyyy-mm-dd format} {file extension, e.g., jpg}" exit 1 fi # Assign command line args to variables prefix=$1 current_date=$2 extension=$3 # Validations if ! [[ $current_date =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}$ ]]; then echo "Date format is invalid. Please use yyyy-mm-dd format." exit 1 fi if [[ $extension == .* ]]; then echo "Please provide the file extension without a leading period." exit 1 fi if [[ -z $prefix ]]; then echo "Please provide a non-empty prefix." exit 1 fi # Loop through all files with the given extension in the current directory # # By default, if you use a pattern that doesn't match any filenames (like *.jpg # when there are no .jpg files), bash will pass the pattern itself as an # argument to commands. For example, if there are no .jpg files in your # directory and you use the *.jpg pattern in a loop or command, the loop or # command will receive *.jpg as an input, which is probably not what you want. shopt -s nullglob i=1 for file in *$extension; do # Skip if the file is not a regular file if [[ ! -f $file ]]; then continue fi # Generate the correlative number with leading zeros printf -v suffix "%02d" $i # Rename the file (-- is end of command line options) mv -- "$file" "${prefix}-${current_date}_${suffix}.${extension}" # Increment the counter ((i++)) done shopt -u nullglob echo "Renaming complete!"