The disclaimer and MIT license given at the bottom of this page applies to all code snippets shown on this page.

Remove duplicate files

This zsh script takes two directories as input arguments. Files that are in the first directory are searched recursively in the second directory by their filenames. If duplicates are found, they are deleted in the first directory after user confirmation.

# Files that are in the first directory $1 are searched recursively in
# the second directory $2. If dupes are found, they are deleted with
# confirmation in the first directory.

# Directory to read filenames from (passed as the first argument)
filenames_dir="$1"

# Directory to search in (passed as the second argument)
search_dir="$2"

# Read filenames from the specified directory
filenames=("$filenames_dir"/*)

# Loop through each filename in the list
for filename in "${filenames[@]}"; do
    # Get just the filename without the path
    base_filename="$(basename "$filename")"

    # Find the full path of the found file
    found_file=$(find "$search_dir" -type f -name "$base_filename")

    if [[ -n "$found_file" ]]; then
        printf "\\n----------------------\\n"
        printf "Found duplicate \\n\\n$found_file\\n\\n"
        echo -n "Do you want to delete it from $filenames_dir? (y/n): " # comment out to remove confirmation
        read choice # comment out to remove confirmation
        # choice="y" # uncomment to remove confirmation (be careful, this will directly delete files)
        if [[ "$choice" == [Yy] ]]; then
            echo ""
            rm "$filename"
            # echo "rm $filename"
            printf "\\nDeleted:\\n$filename\\n\\n"
        fi
    fi
done

License and disclaimer

MIT License

Copyright (c) 2023 Mitchell Hashimoto

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.