Remove duplicate files from TargetFolder that are also in SourceFolder -- if they have same filename This is a clarified version of a question asked two days ago.
I'd like to remove files from TargetFolder  that are also in SourceFolder  (what I was calling a reference directory) --  but only if they have the same name.  I'd like it to operate recursively,  on a Mac (high sierra).  Thanks.
I used this script with the latest Bash 5. You should be fine with the stock install. Please be careful. You should be able to set your directories as &quot;dir1&quot; (source) and &quot;dir2&quot; (destination files that will be removed if they exist in source).
Basically, the &quot;getall&quot; function will create two arrays of recursive files like: &quot;/fullpath/filename.&quot; The ladder part will trim the paths to the filenames for comparison, compare the file names and file sizes, and list or delete duplicates.
You should always make backups and test the script on dummy files. Hopefully you can edit the script to meet your needs. You can simply copy and paste into terminal after you choose your directories.
#!/bin/bash
#This tool is for removing duplicate files among backup directories.
#compares two directory trees, matches filenames, calc/ compare sizes to determine duplicates.

unset _my_array
unset _my_array_1
unset _my_array_2

function getall() {
  local home=&quot;$(pwd)&quot;
  for file in *; do
    if [[ -d $file ]]; then
      cd &quot;$file&quot;
      getall
      cd &quot;$home&quot;
    else
      ! [[ -f $file ]] &amp;&amp; break   #ensure the entry added is a file
      _my_array+=(&quot;$(pwd)/$file&quot;) #add path/file to array
    fi
  done
}

dir1=&quot;/User/user/Downloads/somefolder&quot;
dir2=&quot;/Users/user/Downloads/someotherfolder&quot;

#generate recurisve full paths array for each directory
clear
echo &quot;parsing tree 1&quot;

unset _my_array
cd &quot;$dir1&quot; || exit
getall                          #create dir list 1
_my_array_1=(&quot;${_my_array[@]}&quot;) #create array 1

echo &quot;parsing tree 2&quot;

unset _my_array
cd &quot;$dir2&quot; || exit
getall                          #create dir list 2
_my_array_2=(&quot;${_my_array[@]}&quot;) #create array 2

#comparison process
for filename1 in &quot;${_my_array_1[@]}&quot;; do
  trim_name_1=&quot;${filename1##*/*/}&quot;
  for filename2 in &quot;${_my_array_2[@]}&quot;; do
    trim_name_2=&quot;${filename2##*/*/}&quot;
    if [[ &quot;$trim_name_1&quot; == &quot;$trim_name_2&quot; ]]; then
      size1=&quot;$(stat -f %z &quot;$filename1&quot;)&quot;
      size2=&quot;$(stat -f %z &quot;$filename2&quot;)&quot;
      if [[ $size1 == $size2 ]]; then
        echo &quot;SAME $filename1&quot;
        echo &quot;     $filename2&quot;
        #  rm &quot;$filename2&quot; #uncomment to REMOVE FILES PERMANENTLY
        break
      fi
    fi
  done
done