I have two directories called thumb and thumb2. They contain the same file names but are different in size. Unfortunatelly there are some files in thumb2 that are not in thumb which need to be removed.

$ ls ../thumb2 | wc -l

$ ls ../thumb | wc -l

I am searching for a command line command that will delete all files from thumb2 that are not also in thumb.

Does anybody have an idea on how to do that?

2 Answers 2


I have tested this solution with a small sample, but be sure to back up your directories before you try:

cd ../thumb2
for f in *; do test -e ../thumb/$f || echo rm $f; done

I don't have a directory with thousands of files, so I don't know if this command works for such a large sample. Please try it out after you backed up your directories. Once you are sure that the command works properly, remove the echo command.


Here is a modified version of Glenn's excellent solution:

diff thumb thumb2 | \
while read field1 field2 dir filename; do 
    [[ $dir = "thumb2:" ]] && echo rm "thumb2/$filename"

You can also call upon diff to examine directory contents:

diff thumb thumb2 |
while read line; do
  case "$line" in
    "Only in thumb2: "*) echo rm "thumb2/${line#*: }" ;;

Remove echo if you're satisfied it's working.

  • +1 I did not know that diff can compare directories.
    – Hai Vu
    Mar 9, 2012 at 16:12

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.