Find Files with the Same Name as the Directory

bashdiff()findgrepshell-script

I have the next problem:

Directory Example1 has three files: Example1, Things and Pictures.

Directory Example2 has three files: Example2, Example3 and Pictures.

I need a list showing only the files that match the directory name, this is: Example1 and Example2. I have tried with diff, find, locate and ls… but I have not achieved anything.

Best Answer

Since there are generally fewer directories than files, let's look for all directories and then test whether they contain the required filename.

find . -type d -exec sh -c '
    for dirpath do
        filepath="$dirpath/${dirpath##*/}"
        [ -f "$filepath" ] && printf "%s\n" "$filepath"
    done' sh {} +

This would print the pathnames of all regular files (and symbolic links to regular files) that is located in a directory that has the same name as the file.

The test is done in a short in-line sh -c script that will get a number of directory pathnames as arguments. It iterates over each directory pathname and constructs a file pathname with the name that we're looking for. The ${dirpath##*/} in the code could be replaced by $(basename "$dirpath").

For the given example directory structure, this would output

./Example1/Example1
./Example2/Example2

To just test for any name, not just regular files, change the -f test to a -e test.