How to copy "just files" recursively
20,904
Solution 1
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.
Solution 2
With zsh, thanks to **
for recursive globbing and the glob qualifier .
to match only regular files:
cp -p folder0/**/*(.) targetfolder
Solution 3
Or using xargs
find folder0 -type f | xargs -I {} cp -v {} targetfolder;
Use -v to show what is hapenning.
Related videos on Youtube
![SirSaleh](https://i.stack.imgur.com/4S9Kf.jpg?s=256&g=1)
Author by
SirSaleh
Updated on September 18, 2022Comments
-
SirSaleh almost 2 years
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 usedcp --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
-
codeforester over 7 yearsCan you please add explanation of why the GNU variant is more efficient?
-
Satō Katsura over 7 years@codeforester Running
cp
once vs. running it for each file.-t
is needed becausefind ... -exec cp {} targetfolder +
is invalid syntax ({}
must come at the end). -
SirSaleh over 7 yearsHaha! Thanks. You saved me. It works :) ... but what
\;
do at end of first? -
Satō Katsura over 7 years@SirSaleh It marks the end of the
-exec
ed command.