moodym
moodym

Reputation: 41

Find files where prefix and suffix match

I would like to find all files where the first part of the filename (up to the first .) matches the file extension (after the last .).

For example, the following files would match:

cat.cat
cat.txt.cat

Whereas cat.txt.asm would not.

How can I do this using find?

Upvotes: 0

Views: 1850

Answers (3)

P....
P....

Reputation: 18351

    find . -type f -iname "*" | awk -F/ '{print $2}' |awk -F. '$1==$NF'

Or

    ls -1 | awk -F. '$1==$NF'

Upvotes: 1

Destrif
Destrif

Reputation: 2134

Sorry this is better:

You could just simply do this:

for exemple find toto.tata.toto specific:

find . -regex ".*\(toto\)[^\/]*\.\1"

Generic:

find . -regex ".*/\([^./\]*\)[^\/]*\.\1"

Upvotes: -1

choroba
choroba

Reputation: 241768

Use the -regex option to find:

find -regex '.*/\([^.]+\)\.\(.*\.\)?\1'
  • .*/ matches the path to the file
  • \([^.]+\) captures anything up to the first dot (+ means at least one character)
  • \(.*\.\)? matches the middle part, i.e. anything ending in a dot, but the whole thing is optional
  • \1 means the first capture is repeated

Might be more readable in the egrep dialect:

find -regextype egrep -regex '.*/([^.]+)\.(.*\.)?\1'

Upvotes: 4

Related Questions