find and copy file using Bash [duplicate]

Anybody has an alternate way of finding and copying files in bash than:

find . -ctime -15 | awk '{print "cp " $1 " ../otherfolder/"}' | sh

I like this way because it's flexible, as I'm building my command (can by any command) and executing it after.

Are there other ways of streamlining commands to a list of files?

Thanks

13.10.2009 18:32:15
Similar Q&A 1+1/2 years later: stackoverflow.com/q/5241625/1172302
Nikos Alexandris 15.08.2012 04:27:54
6 ОТВЕТОВ
РЕШЕНИЕ

I would recommend using find's -exec option:

find . -ctime 15 -exec cp {} ../otherfolder \;

As always, consult the manpage for best results.

85
13.10.2009 18:36:36
The find man page suggests using single quotes around the braces since it may get misinterpreted without them.
Jonathan Sternberg 15.05.2010 05:59:59
You should replace \; with + to avoid running a cp every time.
Reinstate Monica Please 13.07.2014 23:05:05
@BroSlow Not sure why but this only works with \; and with + I get 'missing argument for -exec'.
user234932 7.01.2016 15:57:20
what if all the files have the same name (im.png)? Can I put them in the same directory while renaming, such as im_1.png, im_2.png, im_3.png...
MrMartin 15.01.2019 13:33:08
@user234932 you need to use an alternate way to pass destination to cp: find … -exec cp -t <target_directory> {} + should work
Mr. Tao 21.11.2019 13:34:19

I usually use this one:

find . -ctime -15 -exec cp {} ../otherfolder/ \;
8
13.10.2009 18:37:39

-exec is likely the way to go, unless you have far too many files. Then use xargs.

-1
13.10.2009 18:38:37
This could be a comment to an accepted response or supply examples for each method you've mentioned.
harperville 16.02.2020 17:16:31

You can do it with xargs:

$ find . -ctime 15 -print0 | xargs -0 -I{} cp {} ../otherfolder

See also grep utility in shell script.

6
23.05.2017 12:18:02
This has the advantage of being faster than find -exec because it doesn't create a new cp process for each file. However if you have GNU find you can do find -exec ... + instead of find -exec ... ';' for the same effect :)
hobbs 14.10.2009 07:18:54

If your cp is GNU's:

find . -ctime 15 -print0 | xargs --no-run-if-empty -0 cp --target-directory=../otherfolder
8
6.03.2020 11:28:43
With this syntax I get cp: missing operand. If I use the syntax provided by @andrey-vlasovskikh (-I{} -cp {} otherfolder) I don't receive this error.
harperville 16.02.2020 17:14:41
Updated the answer to cover that case (when find produces no output).
Idelic 6.03.2020 11:29:33

Use this for copy and many other things:

for f in $(find /apps -type f -name 'foo'); do cp ${f} ${f}.bak; cmd2; cmd3; done;
1
30.06.2019 16:02:02
Shouldn't there be a $ before (find /apps -type f -name 'foo')? Thanks.
Shaohua Li 26.08.2018 03:53:29