Skip to content

Instantly share code, notes, and snippets.

@mortezaf
Created April 9, 2024 17:46
Show Gist options
  • Save mortezaf/0645d988f2eb880ebc655b014e7ba9fd to your computer and use it in GitHub Desktop.
Save mortezaf/0645d988f2eb880ebc655b014e7ba9fd to your computer and use it in GitHub Desktop.
Organize Media Files by Date and Type in Linux
#!/bin/bash
# Source directory (replace with your actual path)
source_dir="/media/morteza/740AAD9378D989B4"
# Destination directory (replace with your actual path)
destination_dir="/home/morteza/oldfiles"
# Create destination directory if it doesn't exist
mkdir -p "$destination_dir"
# Loop through each media file in the source directory
find "$source_dir" -type f \( -iname "*.jpg" -o -iname "*.jpeg" -o -iname "*.mp4" -o -iname "*.mov" -o -iname "*.avi" -o -iname "*.3gp" -o -iname "*.wmv" -o -iname "*.dat" \) | while read -r file; do
# Get the parent folder name
parent_folder=$(basename "$(dirname "$file")")
# Get the creation year of the file
file_year=$(date -d @"$(stat -c %Y "$file")" +%Y)
# Get the file extension without the leading dot
file_extension=$(echo "$file" | awk -F'.' '{print tolower($NF)}' | sed 's/^\.//')
# Create destination directory based on file extension, file creation year, parent folder, and file name
mkdir -p "$destination_dir/$file_extension/$file_year/$parent_folder"
# Get the file name without the path
file_name=$(basename "$file")
# Copy the file to the destination directory
rsync -a "$file" "$destination_dir/$file_extension/$file_year/$parent_folder/$file_name"
done
@mortezaf
Copy link
Author

mortezaf commented Apr 9, 2024

This Bash script helps organize media files such as images and videos by their creation date and file type. It recursively searches a source directory for supported media files (e.g., JPG, JPEG, MP4, MOV, etc.), and then organizes them into a structured directory hierarchy based on their creation date, parent folder name, and file type.
Features

1.Supports organizing various media file types including JPG, JPEG, MP4, MOV, AVI, 3GP, WMV, and DAT.
2.Creates destination directories based on the file extension, creation year, parent folder, and filename.
3.Utilizes rsync for efficient copying of files while preserving their attributes.

Usage

  1. Set the source_dir variable to the directory containing the media files you want to organize.
  2. Set the destination_dir variable to the desired destination directory where the organized files will be copied.
  3. Execute the script. It will scan the source_dir, organize the files, and copy them to the specified destination_dir.

Example Directory Structure:

- destination_dir/
  - jpg/
    - 2019/
      - parent_folder/
        - filename.jpg
    - 2020/
      - another_parent/
        - image.jpg
  - mp4/
    - 2018/
      - video_folder/
        - video.mp4

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment