Good start. Your delete will work. Checkout find's fprint.
There is a command line trashcan utility (trash-cli), but I haven't used it.
What about a different tack - move to a NEWDIR, verify, and then delete NEWDIR when you know all the files are not wanted (rm -r NEWDIR).
When testing put echo's in front of commands or check the man page to see if there is something like a --dry-run option.
When done, you may also want to delete the current directories, if they are empty (find . -type d -empty)
Regarding the example below, $1 is input argument 1. The script is expecting the file extension (ie., jpg), although no checking is done. You will get an error if not supplied (:? - See bash man page
Parameter Expansion). Just run the script for each file type. ./SCRIPT mp4 ... ./SCRIPT avi, etc. Check directory locations. I made assumptions.
Code: Select all
#!/bin/bash
#set -u
#set -x
scriptname="${0##*/}"
ft="${1:?Error: Missing file type}" # Input argument - file type extension
dir='.' # media directory
ftdir="${dir}/delete-${ft}/" # file type NEWDIR
ftlist="${dir}/list-${ft}" # file type list
ftlistmv="${dir}/list-${ft}-mv" # file type list for mv
ftnum=1
ftdupnum=1
if ! mkdir "${ftdir}"; then
printf -- '%s: Error: mkdir failed - %s\n' "${scriptname}" "${ftdir}"
exit 1
fi
echo "Processing ${ft} files"
### Option 1: If you know for sure there are no duplicate file names, or there are no subdirectories, this would work.
#
find "${dir}" \( -path "${ftdir}" \) -prune -o -type f -name "*.${ft}" -fprint "${ftlist}" -exec mv --target-directory="${ftdir}" '{}' \+
exit 0
### Option 2: Comment out the find and exit above if you think there are duplicate file names.
# Prevent overwrite of duplicate file names in subdirectories. Just tack on an integer.
# Files are separated with a null.
# ${file##*/}" - See bash parameter expansion. This removes everything on the left until the last slash, basically the basename.
#
while IFS='' read -r -d $'\0' file; do
if [[ -e "${ftdir}${file##*/}" ]]; then
mv -v "${file}" "${ftdir}${file##*/}-$((ftdupnum++))" >> "${ftlist}-mv" # Duplicate file name
else
mv -v --target-directory="${ftdir}" "${file}" >> "${ftlistmv}" # No duplicate
fi
((ftnum++))
done < <(find "${dir}" \( -path "${ftdir}" \) -prune -o -type f -name "*.${ft}" -fprint "${ftlist}" -print0)
echo "Processed $((ftnum-1)) files"
echo "Duplicate file names $((ftdupnum-1))"
Some folks use find and pipe it to xargs, some use rsync. Bash has a shopt option called globstar that could also be used to create a pattern and transverse directories with a for loop.