this repo has no description
at main 2.5 kB view raw
1#!/bin/bash 2 3# File watcher and renamer 4# This script watches a folder and automatically renames new files to an 8-digit UUID format 5 6# Check if folder path is provided 7if [ $# -ne 1 ]; then 8 echo "Usage: $0 <folder_path>" 9 exit 1 10fi 11 12WATCH_DIR="$1" 13 14# Check if the directory exists 15if [ ! -d "$WATCH_DIR" ]; then 16 echo "Error: Directory '$WATCH_DIR' does not exist." 17 exit 1 18fi 19 20# Function to generate an 8-digit UUID 21generate_uuid() { 22 # Generate a random 8-digit hexadecimal string 23 uuid=$(openssl rand -hex 4) 24 echo "${uuid:0:8}" 25} 26 27# Function to check if filename already matches our pattern (8 hexadecimal digits + extension) 28is_compliant() { 29 local filename=$(basename "$1") 30 local name_without_ext="${filename%.*}" 31 32 # Check if the name (without extension) is exactly 8 characters and only contains hexadecimal digits 33 if [[ $name_without_ext =~ ^[0-9a-f]{8}$ ]]; then 34 return 0 # Compliant 35 else 36 return 1 # Not compliant 37 fi 38} 39 40# Function to rename a file with an 8-digit UUID 41rename_file() { 42 local filepath="$1" 43 local dir=$(dirname "$filepath") 44 local filename=$(basename "$filepath") 45 local extension="${filename##*.}" 46 47 # If file has no extension, don't add a dot 48 if [ "$extension" = "$filename" ]; then 49 extension="" 50 else 51 extension=".$extension" 52 fi 53 54 # Generate a new UUID 55 local new_uuid=$(generate_uuid) 56 local new_name="${new_uuid}${extension}" 57 local new_path="${dir}/${new_name}" 58 59 # Check if new filename already exists, if so, generate a new one 60 while [ -e "$new_path" ]; do 61 new_uuid=$(generate_uuid) 62 new_name="${new_uuid}${extension}" 63 new_path="${dir}/${new_name}" 64 done 65 66 # Rename the file 67 mv "$filepath" "$new_path" 68 echo "Renamed: $filename -> $new_name" 69} 70 71# Process existing files first 72echo "Checking existing files in $WATCH_DIR..." 73find "$WATCH_DIR" -type f -not -path "*/\.*" | while read file; do 74 if ! is_compliant "$file"; then 75 rename_file "$file" 76 fi 77done 78 79# Start monitoring the directory for changes 80echo "Watching $WATCH_DIR for new files..." 81fswatch -0 "$WATCH_DIR" | while read -d "" event; do 82 # Skip hidden files and directories 83 if [[ $(basename "$event") == .* ]]; then 84 continue 85 fi 86 87 # Only process files, not directories 88 if [ -f "$event" ]; then 89 # If the file is not compliant, rename it 90 if ! is_compliant "$event"; then 91 rename_file "$event" 92 fi 93 fi 94done