Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

I have the following directory structure.

dirA/[fileA, someB, barC, fileD, someE, barF] dirB/[fileA, barC, someE]

I want to copy only files from dirA to dirB which are already present in dirB. How do I do this selective copy?

share|improve this question

1 Answer 1

up vote 2 down vote accepted

You could for instance use the find command with the -exec option. You'd probably use some syntax like the following (has to be run in dirB, and be aware that it's recursive):

find ./ -type f -exec cp '../dirA/{}' ./ \;

The -type f tells find to only take into account regular files, the -exec says: run the following command on every file. The \; at the end terminates the command to be run. The {} is a placeholder that is replaced by the actual filename by find. Check out the man page of find for details and other usage examples.

Here's what happens on my PC:

desktop:~$ mkdir dirA
desktop:~$ mkdir dirB
desktop:~$ cd dirA
desktop:~/dirA$ touch foo bar this
desktop:~/dirA$ cd ..
desktop:~$ cd dirB
desktop:~/dirB$ touch bar this
desktop:~/dirB$ find ./ -type f -exec cp -v '../dirA/{}' ./ \;

»../dirA/./this“ -> »./this“
»../dirA/./bar“ -> »./bar“
share|improve this answer
    
Thanks, but it seems to be copying all files from dirA. I want to copy only files from dirA which are already present in dirB. –  Rpj Mar 27 '13 at 9:41
    
If you run it while you are in dirB it should really only copy files that are already there. You can add -v after cp to see which files it is copying. I'll update my above post with a usage example. –  soulsource Mar 27 '13 at 10:08

Your Answer

 
discard

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.