3

Suppose I have this structure for folder0 and subfolders and files in it.

   folder0
      subfolder01
        file011
        file012
      subfolder02
        file021
      file01
      file02

I want to copy all files in main folder folder0 to somewhere else, such that all file be in one directory? How Can I do that? I used

cp --recursive folder0address targetfolderaddress

But subfolders copied to target folder. I just want all files in directory and sub directories not folders. I mean something like the below in target folder:

targetfolder
  file011
  file012
  file021
  file01
  file02
6

Use find:

find folder0 -type f -exec cp {} targetfolder \;

With GNU coreutils you can do it more efficiently:

find folder0 -type f -exec cp -t targetfolder {} +

The former version runs cp for each file copied, while the latter runs cp only once.

  • 1
    Can you please add explanation of why the GNU variant is more efficient? – codeforester Mar 15 '17 at 18:22
  • 2
    @codeforester Running cp once vs. running it for each file. -t is needed because find ... -exec cp {} targetfolder + is invalid syntax ({} must come at the end). – Satō Katsura Mar 15 '17 at 18:29
  • Haha! Thanks. You saved me. It works :) ... but what \; do at end of first? – SirSaleh Mar 15 '17 at 19:03
  • 1
    @SirSaleh It marks the end of the -execed command. – Satō Katsura Mar 16 '17 at 7:56
2

With zsh, thanks to ** for recursive globbing and the glob qualifier . to match only regular files:

cp -p folder0/**/*(.) targetfolder
0

Or using xargs

 find folder0 -type f | xargs -I {} cp -v {} targetfolder;

Use -v to show what is hapenning.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.