snippets/sortbooks.sh

67 lines
1.9 KiB
Bash
Raw Normal View History

#!/bin/bash
# Set the current directory as the watched directory
WATCHED_DIR="$(pwd)"
shopt -s nocasematch
# Define source keywords and their corresponding target folder
declare -A KEYWORD_MAP
KEYWORD_MAP["Code"]="Code and Build"
KEYWORD_MAP["Build"]="Code and Build"
KEYWORD_MAP["Software"]="Code and Build"
KEYWORD_MAP["Programming"]="Code and Build"
KEYWORD_MAP["Development"]="Code and Build"
KEYWORD_MAP["SRE"]="SRE"
KEYWORD_MAP["DevOps"]="DevOps"
KEYWORD_MAP["Cloud"]="Cloud"
KEYWORD_MAP["UX"]="UX"
KEYWORD_MAP["Business"]="Business"
# Function to find or create a directory for the target keyword
find_or_create_directory_for_target() {
local target="$1"
for DIR in "$WATCHED_DIR"/*/; do
if [[ $(basename "$DIR") == *"$target"* ]]; then
echo "${DIR%/}"
return
fi
done
NEW_DIR="$WATCHED_DIR/$target"
mkdir -p "$NEW_DIR"
echo "$NEW_DIR"
}
# Function to move files based on source keywords
move_files() {
2023-12-29 11:52:27 +00:00
# Delete duplicate files using fdupes
echo "Removing duplicate files in $WATCHED_DIR..."
fdupes -r -N --delete "$WATCHED_DIR"
for FILE in "$WATCHED_DIR"/*.{epub,pdf,mobi,txt}; do
if [[ -f "$FILE" ]]; then
FILENAME=$(basename "$FILE")
for SOURCE_KEYWORD in "${!KEYWORD_MAP[@]}"; do
if [[ "$FILENAME" == *"$SOURCE_KEYWORD"* ]]; then
TARGET_FOLDER="${KEYWORD_MAP[$SOURCE_KEYWORD]}"
DEST_DIR=$(find_or_create_directory_for_target "$TARGET_FOLDER")
echo "Moving '$FILENAME' to '$DEST_DIR'"
mv "$FILE" "$DEST_DIR/"
break
fi
done
fi
done
}
# Initial sorting of files
move_files
# Monitor for new or modified files and then sort them
2023-12-29 11:52:27 +00:00
while inotifywait -r -e create -e moved_to -e modify "$WATCHED_DIR"; do
move_files
done
2023-12-29 11:52:27 +00:00
shopt -u nocasematch