So I was looking around and all I have found is how to do this only if the directory is already made, which is this:

find source -name '*.z' -exec cp {} destination \;

But how can I make a new directory where I want to send these files in the same command? This is what I have tried but with no success:

find source -name '*.z' -exec cp {} | mkdir newDirectory \;
  • 2
    I don't understand why you aren't just using mkdir newDirectory; find … -exec cp {} newDirectory \; Oct 12, 2013 at 23:52

2 Answers 2


One option is to use the install command instead of cp. It has an option to create all of the leading directories.

find source -name '*.z' -exec install -D {} dest \;
  • 1
    On OSX -d must be used instead of capital -D.
    – ccpizza
    Sep 28, 2016 at 16:55

You can't pipe data to mkdir that way. You could do something like this:

find source -name '*.z' -exec sh -c 'mkdir -p newDirectory && cp "$@" newDirectory' _ {} +

or (assuming file names not containing newlines)

find source -name '*.z' | while IFS= read -r foo; do 
   mkdir -p newDirectory;
   cp "$foo" newDirectory;

or if you only want to create one directory, so the name is always the same:

mkdir newDirectory; find source -name '*.z' -exec cp {} newDirectory \;
  • Does find actually change the working directory as it goes? Won't this try making a directory in the same place each time and copy all the files into it? If he wanted them all in one directory, I can't see why he'd need to create the directory as he worked...
    – kurtm
    Oct 12, 2013 at 15:56
  • Is there any way to do the first way without a bash statement? Possibly piped?
    – John
    Oct 12, 2013 at 15:56
  • @kurtm see updated answer, and yes, apparently find changes the CWD as it goes, it will create the directory in the same place.
    – terdon
    Oct 12, 2013 at 15:58
  • @John see updated answer. You cannot pipe data to mkdir.
    – terdon
    Oct 12, 2013 at 15:58
  • @terdon Okay. I wasn't sure since it give relatives paths for output.
    – kurtm
    Oct 12, 2013 at 15:59

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .