Ask Ubuntu is a question and answer site for Ubuntu users and developers. Join them; it only takes a minute:

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 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
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


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.