Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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 \;
share|improve this question
    
I don't understand why you aren't just using mkdir newDirectory; find … -exec cp {} newDirectory \; –  Gilles Oct 12 '13 at 23:52

2 Answers 2

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

find source '*.z' -exec install -D {} dest \;
share|improve this answer

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

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 \;
share|improve this answer
    
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 '13 at 15:56
    
Is there any way to do the first way without a bash statement? Possibly piped? –  John Oct 12 '13 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 '13 at 15:58
    
@John see updated answer. You cannot pipe data to mkdir. –  terdon Oct 12 '13 at 15:58
    
@terdon Okay. I wasn't sure since it give relatives paths for output. –  kurtm Oct 12 '13 at 15:59

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.