Script to delete files with an input for directories and an input for path/file

Hello,

I'm trying to figure out how best to approach this script, and I have very little experience, so I could use all the help I can get. :wall:

I regularly need to delete files from many directories.

A file with the same name may exist any number of times in different subdirectories.
When I perform the deletion, I will have a list of the upper level directories I want to delect the file path from, and a list of pathed files I want to delete from those directories only.

What would be the best way to set this up with the two input files?

For example, I need to delete:

/red/rotten/apple.t
/red/rotten/apple.x
/green/ripe/pear.t
/green/ripe/pear.x
/green/ripe/grapes.t
/green/ripe/grapes.x
/green/rotten/oranges.t
/green/rotten/oranges.x

from

/orchard1/old
/orchard1/new
/orchard2/old
/orchard2/new
/orchard6/old
/orchard6/new
/orchard8/old
/orchard8/new

But I want files with the same names elsewhere to be left alone.

Any assistance will be greatly appreciated! :smiley:

Please post examples from the target directory and explain the deletion rules.

This should get you started you might want to implement more actions (like prompt) and perhaps control which actions occur with command line args check out getopts

if [ $# -ne 2 ]
then
   echo "usage: $0 list_file dir_file"
   exit 1
fi
LIST_FILE=$1
DIR_FILE=$2
if [ ! -f "$LIST_FILE" ]
then
   echo "unable to open list_file: $LIST_FILE"
   exit 2
fi
if [ ! -f "$DIR_FILE" ]
then
   echo "unable to open dir_file: $DIR_FILE"
   exit 3
fi
found=0
for action in list count del
do
    for del_dir in $(cat $DIR_FILE)
    do
        for del_path in $(cat $LIST_FILE)
        do
            [ -f ${del_dir}/${del_path} ] && case $action in
               count) let found=found+1 ;;
               list) echo "  ${del_dir}/${del_path}" ;;
               del) rm ${del_dir}/${del_path} ;;
            esac
        done
    done
    if [ $action = "count" ]
    then
        [ $found -eq 0 ] && echo "No files found to delete" && exit 5
        printf "OK to delete %d file(s) (Y/N)? " $found
        read ans
        [ "$ans" != "Y" -a "$ans" != "y" ] && exit 0
    fi
done

If interactivity is not required, if there are no blank lines in either file, and if your pathnames (both directories and files) do not contain any whitespace:

join -12 -22 dirs files | tr -d ' ' | xargs echo rm -- 

PROCEED WITH CAUTION: I cannot emphasize that enough. If the rm commands printed are acceptable, remove the word "echo" to delete the files. Error messages from non-existent files are harmless. To silence them, append 2>/dev/null (or redirect to some other file).

Regards,
Alister