Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question

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"
share|improve this answer

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.

share|improve this answer
+1 I did not know that diff can compare directories. – Hai Vu Mar 9 '12 at 16:12

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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