Skip to content

Instantly share code, notes, and snippets.

@ChieftainY2k
Last active November 15, 2023 10:02
Show Gist options
  • Save ChieftainY2k/b399fd3bd438eb5afe6986725a4a785b to your computer and use it in GitHub Desktop.
Save ChieftainY2k/b399fd3bd438eb5afe6986725a4a785b to your computer and use it in GitHub Desktop.
Convert filenames based on the modification timestamp (this is important for multimedia files to be sorted right)
#!/bin/bash
set -e
# Directory containing .AVI files
SOURCE_DIR="./"
# Directory where files will be copied
TARGET_DIR="./sorted"
# Create target directory if it doesn't exist
mkdir -p "$TARGET_DIR"
# Initialize a sequence number
seq_num=1
# Array of file extensions to process
extensions=("mov" "avi" "mp4" "MOV" "AVI" "MP4")
# Process each file type
for ext in "${extensions[@]}"; do
# Process each file with the current extension
for file in "$SOURCE_DIR"/*.$ext; do
# Skip if no files are found
[ -e "$file" ] || continue
# Extract the basename of the file (without path and extension)
base_name=$(basename -- "$file" .$ext)
# Replace dots with underscores in base_name
base_name=${base_name//./_}
# Get last modification time from the filesystem in YYYYMMDDHHMMSS format
mod_time=$(stat -c %y "$file" | cut -d '.' -f 1 | tr -d ' :-')
# Format the sequence number with zero-padding to 3 characters
formatted_seq_num=$(printf "%03d" "$seq_num")
# Create new filename with the modification time, modified original name, and sequence number
new_filename="${mod_time}_${formatted_seq_num}_(${base_name}).$ext"
# Copy the file to the target directory with the new name
echo "$file --> $new_filename"
cp "$file" "$TARGET_DIR/$new_filename"
# Increment the sequence number for the next file
((seq_num++))
done
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment