Recursively find files with the same filename

I needed a way to find files with the same filename, but were not identical files. Thankfully Reddit had the solution I was looking for: a combination of find, sort, and while loop with if statements.

https://www.reddit.com/r/bash/comments/fjsr8v/recursively_find_files_with_same_name_under_a/

find . -type f -printf '%f/%p\0' | { sort -z -t/ -k1; printf '\0';} |
while IFS=/ read -r -d '' name file; do
    if [[ "$name" = "$oldname" ]]; then
        repeated+=("$file")  # duplicate file
        continue
    fi
    if (( ${#repeated[@]} > 1)); then
        printf '%s\n' "$oldname" "${repeated[@]}" ''
        # do something with list "${repeated[@]}"
    fi
    repeated=("$file")
    oldname=$name
done

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.