8

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

DIR1:
 - IN89284.wav
 - OUT9920.wav

DIR2:
 - 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?

3 Answers 3

5
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
1
  • 3
    less cryptic. If someone wants a more generic solution then can use diff <(ls -1 ./dir1 | sed 's/\.[a-z]*$//g') <( ls -1 ./dir2 | sed 's/\.[a-z]*$//g') Commented Dec 19, 2020 at 3:49
4

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 root name (remove extension).

Using globbing guarantees a consistent sort order.

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

4

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.

Example:

$ 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)
test2
$ comm -23 <(find dir1 -type f -exec bash -c 'basename "${0%.*}"' {} \; | sort) <(find dir2 -type f -exec bash -c 'basename "${0%.*}"' {} \; | sort)
test1
test3
$ comm -13 <(find dir1 -type f -exec bash -c 'basename "${0%.*}"' {} \; | sort) <(find dir2 -type f -exec bash -c 'basename "${0%.*}"' {} \; | sort)
test4

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.

0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .