2

Im totally newbie in shell script. Im need compare file name in two directories and delete files with same name.

EG:

Directory1/
one
two
three
four

Directory2/
two
four
five

After run script the directories will be:

Directory1/
one
three

Diretory2/
five

Thanks

3
  • I've tried diff Directory1/ Directory2/ but it shows me singular files in each directory and not yhe duplicate files. Commented Nov 24, 2011 at 23:41
  • You just need to delete files with same name? Different files can have same names. Correct approach would be to use cksum or md5 to identify if the files are indeed duplicates. Commented Nov 25, 2011 at 0:34
  • only same name its allright. the content its not important in my case. thaks. Commented Nov 25, 2011 at 1:36

2 Answers 2

3

test -f tests if a file exists:

cd dir1
for file in *
do
    test -f ../dir2/$file && rm $file ../dir2/$file
done
cd ..
Sign up to request clarification or add additional context in comments.

Comments

2

Quick and dirty:

while read fname
do 
    rm -vf Directory{1,2}/"$fname"
done < <(sort 
              <(cd Directory1/ && ls) 
              <(cd Directory2/ && ls) | 
         uniq -d)

This assumes a number of things about the filenames, but it should get you there with the input shown, and similar cases.

Tested too, now:

mkdir /tmp/stacko && cd /tmp/stacko
mkdir Directory{1,2}
touch Directory1/{one,two,three,four} Directory2/{two,four,five}

Runnning the command shows:

removed `Directory1/four'
removed `Directory2/four'
removed `Directory1/two'
removed `Directory2/two'

And the resulting tree is:

Directory1/one
Directory1/three

Directory2/five

2 Comments

why double less than is used < < ?
< means input redirection, <(cmd) means process substitution (open the output of a command like a file(descriptor)); < <(cmd) therefore redirects input from a pseudo-file (pipe) that represents the output of cmd.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.