I've got two directories with similar file names but different extensions. Here's an example:

 - IN89284.wav
 - OUT9920.wav

 - IN89284.mp3
 - OUT9920.mp3

I want to compare these directories but ignore the file extensions, so in that case they would be the same. How can I do that? I guess that I'd have to loop through the first directory, trim each file name (cut the extension) and then search for it in the second directory. Is there any better way to do that?


With zsh:

diff -u <(cd dir1 && printf '%s\n' **/*(D:r)) \
        <(cd dir2 && printf '%s\n' **/*(D:r))

(D) to include dot-files (hidden files), :r to get the rest (remove extension).

Using globbing guarantees a consistent sort order.

(that assumes file names don't have newline characters).


You could use this command:

comm -12 <(find dir1 -type f -exec bash -c 'basename "${0%.*}"' {} \; | sort) <(find dir2 -type f -exec bash -c 'basename "${0%.*}"' {} \; | sort)

This uses find to list all the files in each directory, then basename and parameter substitution to strip off the directory names and file extensions. comm compares the two lists.


$ tree
|-- dir1
|   |-- test1.txt
|   |-- test2.txt
|   `-- test3.txt
`-- dir2
    |-- test2.txt
    `-- test4.txt

$ comm -12 <(find dir1 -type f -exec bash -c 'basename "${0%.*}"' {} \; | sort) <(find dir2 -type f -exec bash -c 'basename "${0%.*}"' {} \; | sort)
$ comm -23 <(find dir1 -type f -exec bash -c 'basename "${0%.*}"' {} \; | sort) <(find dir2 -type f -exec bash -c 'basename "${0%.*}"' {} \; | sort)
$ comm -13 <(find dir1 -type f -exec bash -c 'basename "${0%.*}"' {} \; | sort) <(find dir2 -type f -exec bash -c 'basename "${0%.*}"' {} \; | sort)

comm -12 will show all the filenames common to both directories. comm -23 will show all the filenames unique to dir1, comm -13 will show the filenames unique to dir2.

diff  <(ls -1 ./dir1 | sed s/.wav//g) <( ls -1 ./dir2 | sed s/.mp3//g) 

list directory and place each file on a separate line

   ls -1 

remove the file extension

    sed s/.wav//g

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.