Idea

I have a bunch of video files and I want to sort them based on creation date

Solution concept

  • scan the folder for video file types
  • find files without datetime stamp and move them to folder _

What to do

  1. Create bash script nano your-file-name.sh
  2. Paste code
#!/bin/bash

# Check for the input directory
if [ "$#" -eq 0 ]; then
    read -p "Enter the directory containing video files: " directory
else
    directory=$1
fi

# Check if the directory exists
if [[ -z "$directory" ]]; then
    echo "You must provide a directory path."
    exit 1
fi
if [ ! -d "$directory" ]; then
    echo "Directory does not exist."
    exit 1
fi

# Video file extensions
declare -a video_types=('avi' 'mp4' 'mov' 'wmv' 'flv' 'mkv')

# Generate file pattern for find command
file_pattern=""
for ext in "${video_types[@]}"; do
    if [[ -z "$file_pattern" ]]; then
        file_pattern="-iname *.$ext"
    else
        file_pattern="$file_pattern -o -iname *.$ext"
    fi
done

# Find and process video files
echo "Scanning for video files in $directory ..."
find "$directory" -type f \( $file_pattern \) -print0 | while IFS= read -r -d $'\0' filename; do
    # Use ffprobe to find the creation_time metadata
    creation_time=$(ffprobe -v error -show_entries format_tags=creation_time -of default=noprint_wrappers=1:nokey=1 "$filename")

    if [[ -z "$creation_time" ]]; then
        echo "No creation time found for $filename."
    else
        # Extract year and month from the creation_time
        year=$(echo "$creation_time" | cut -d '-' -f 1)
        month=$(echo "$creation_time" | cut -d '-' -f 2)
        time_folder="${year}${month}"

        # Directory for sorted files by year and month
        sorted_dir="${directory}/${time_folder}"

        # Ensure the directory exists
        if [ ! -d "$sorted_dir" ]; then
            mkdir "$sorted_dir"
        fi

        echo "Moving $filename to $sorted_dir based on creation date."
        mv "$filename" "$sorted_dir/"
    fi
done
  1. After script execution you will get the message Enter the directory containing video files:
  2. Paste relative path to directory.