Linux – Find all files with the same name

findlinux

I've a lot of files with the same name in different folders. How can I find all the paths and write them in a text file?

Best Answer

This will handle the general case where you know that there are duplicate file names but you don't know what they are:

find -type f -print0 |
    awk -F/ 'BEGIN { RS="\0" } { n=$NF } k[n]==1 { print p[n]; } k[n] { print $0 } { p[n]=$0; k[n]++ }'

Within the awk script, we handle file paths that are NULL terminated (so we can process file names that might contain newlines), with $0 as the current file pathname. The variable n holds the file name component. k[] is a hash (keyed by n) that counts the number of occurrences of this file name, and p[] is another hash (also keyed by n) that holds the first corresponding full pathname.

Example

# Preparation
mkdir -p tmp/a tmp/b
touch tmp/a/xx tmp/a/yy tmp/b/yy tmp/b/zz

# Do it
find tmp -type f -print0 |
    awk -F/ 'BEGIN { RS="\0" } { n=$NF } k[n]==1 { print p[n]; } k[n] { print $0 } { p[n]=$0; k[n]++ }'

tmp/a/yy
tmp/b/yy

# Tidyup
rm -rf tmp