script for sorting downloads automatically

This commit is contained in:
SansGuidon 2023-12-29 12:11:35 +01:00
parent 786b7ee7d6
commit 04979e25f6

62
sortbooks.sh Executable file
View File

@ -0,0 +1,62 @@
#!/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() {
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
while inotifywait -e create -e moved_to -e modify "$WATCHED_DIR"; do
move_files
fdupes -r -N --delete .
done