How to copy one file to a bunch of directories using find and cp

By Alvin J. Alexander, devdaily.com

Did you ever need to take one file and copy it to a whole bunch of other directories? I had this problem recently when I changed some of the header files on the devdaily.com web site. I had a file named ddhead.html, and I needed to copy it to a bunch of subdirectories. Using Unix, Linux, or Cygwin this turns out to be really easy. I just used the Unix/Linux find command, in combination with the cp command. Once I figured out the right syntax, I was able to copy the file to nearly 500 directories in just a second or two.

Here's how I did it:

find dir1 dir2 dir3 dir4 -type d -exec cp ddhead.html {} \;

Here's what this command does:

  1. First, I use the find command, and I tell it to look in four sub-directories (dir1, dir2, dir3 and dir4).
  2. I tell it to find only directories (-type d).
  3. I then issue the copy (cp) command, and copy the file ddhead.html to each directory that is found, one directory at a time.

The crazy syntax at the end of the command line is something that you have to do with the find command. Honestly, I don't know too much about it, other than the fact that it is required when you do something like this. If you're really interested you can find more details about the find command at this find command man page listing.


devdaily logo