101 lines
2.1 KiB
Bash
Executable File
101 lines
2.1 KiB
Bash
Executable File
#!/usr/bin/env bash
|
|
|
|
set -euo pipefail
|
|
|
|
DRYRUN=0
|
|
TARGET="."
|
|
|
|
if [[ "$1" == "--dry-run" ]]; then
|
|
DRYRUN=1
|
|
TARGET="${2:-.}"
|
|
else
|
|
TARGET="${1:-.}"
|
|
fi
|
|
|
|
LOGFILE="grouping_log_$(date +%Y%m%d_%H%M%S).txt"
|
|
touch "$LOGFILE"
|
|
|
|
dedupe_target() {
|
|
local path="$1"
|
|
|
|
if [[ ! -e "$path" ]]; then
|
|
echo "$path"
|
|
return
|
|
fi
|
|
|
|
local dir
|
|
dir="$(dirname "$path")"
|
|
|
|
local base
|
|
base="$(basename "$path")"
|
|
|
|
local name="${base%.*}"
|
|
local ext="${base##*.}"
|
|
|
|
local n=1
|
|
local candidate
|
|
|
|
while true; do
|
|
candidate="$dir/$name.$n.$ext"
|
|
[[ -e "$candidate" ]] || break
|
|
((n++))
|
|
done
|
|
|
|
echo "$candidate"
|
|
}
|
|
|
|
#find "$TARGET" -type f -maxdepth 1 | while IFS= read -r file; do
|
|
for file in "$TARGET"/*; do
|
|
[[ -f "$file" ]] || continue
|
|
|
|
base="$(basename "$file")"
|
|
|
|
# skip if no artist-title pattern
|
|
[[ "$base" != *" - "* ]] && continue
|
|
|
|
artist="${base%% - *}"
|
|
|
|
# remove "feat." / "ft." sections
|
|
artist="$(sed -E 's/[[:space:]]+(feat|ft)\.?[[:space:]].*$//I' <<< "$artist")"
|
|
|
|
# split on common artist separators and keep first
|
|
artist="$(sed -E 's/[[:space:]]*(,|&| x | X u)[[:space:]]*.*$//' <<< "$artist")"
|
|
|
|
# trim whitespace
|
|
artist="$(sed 's/^[[:space:]]*//;s/[[:space:]]*$//' <<< "$artist")"
|
|
|
|
# lowercase
|
|
artist_lc="$(tr '[:upper:]' '[:lower:]' <<< "$artist")"
|
|
|
|
target_dir="$TARGET/$artist_lc"
|
|
target="$target_dir/$base"
|
|
|
|
# skip if artist extraction failed
|
|
[[ -z "$artist_lc" ]] && continue
|
|
|
|
target="$(dedupe_target "$target")"
|
|
|
|
if [[ "$target" != "$file" ]]; then
|
|
if [[ "$DRYRUN" == "1" ]]; then
|
|
echo "[DRY]"
|
|
echo " OLD: $file"
|
|
echo " NEW: $target"
|
|
echo
|
|
|
|
#Super lean dry run debug mode to spot leftovers
|
|
#echo "$target_dir"
|
|
else
|
|
mkdir -p "$target_dir"
|
|
|
|
echo "Renaming"
|
|
echo " OLD: $file"
|
|
echo " NEW: $target"
|
|
echo
|
|
|
|
mv -n "$file" "$target"
|
|
|
|
echo "$file -> $target" >> "$LOGFILE"
|
|
fi
|
|
fi
|
|
done
|