It was not specified, but here is a solution without regular expressions if anybody is interested.
We can use find . -type f
to just get files, then utilize dirname
and basename
to write the conditional. The utilities have the following behavior:
$ find . -type f
./dir2/spam/spam.pdf
./dir2/dir2.tex
./dir3/dir3.pdf
./dir3/eggs/eggs.pdf
./dir1/dir1.pdf
./dir1/dir1.txt
basename
returns just the filename after the last /
:
$ for file in $(find . -type f); do basename $file; done
spam.pdf
dir2.tex
dir3.pdf
eggs.pdf
dir1.pdf
dir1.txt
dirname
gives the entire path up to the final /
:
$ for file in $(find . -type f); do dirname $file; done
./dir2/spam
./dir2
./dir3
./dir3/eggs
./dir1
./dir1
Therefore, basename $(dirname $file)
gives the parent directory of the file.
$ for file in $(find . -type f); do basename $(dirname $file) ; done
spam
dir2
dir3
eggs
dir1
dir1
Solution
Combine the above to form the conditional "$(basename $file)" = "$(basename $(dirname $file))".pdf
, then only print each result from find
if that conditional returns true.
$ while read file; do if [ "$(basename "$file")" = "$(basename "$(dirname "$file")")".pdf ]; then echo $file; fi done < <(find . -type f)
./dir2/spam/spam.pdf
./dir3/dir3.pdf
./dir3/eggs/eggs.pdf
./dir1/dir1.pdf
./Final Thesis/grits/grits.pdf
./Final Thesis/Final Thesis.pdf
In the above example, we've added a directory/file with spaces in the name to treat that case (thanks to @Kusalananda in the comments)