54

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

jww
  • 97,681
  • 90
  • 411
  • 885
Wadih M.
  • 12,810
  • 7
  • 47
  • 57

6 Answers6

122

I would recommend using find's -exec option:

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

As always, consult the manpage for best results.

asveikau
  • 39,039
  • 2
  • 53
  • 68
16

I usually use this one:

find . -ctime -15 -exec cp {} ../otherfolder/ \;
tangens
  • 39,095
  • 19
  • 120
  • 139
13

If your cp is GNU's:

find . -ctime 15 -print0 | xargs --no-run-if-empty -0 cp --target-directory=../otherfolder
Idelic
  • 14,976
  • 5
  • 35
  • 40
10

You can do it with xargs:

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

See also grep utility in shell script.

Community
  • 1
  • 1
Andrey Vlasovskikh
  • 16,489
  • 7
  • 44
  • 62
  • 1
    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 Oct 14 '09 at 07:18
4

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;
Vlad
  • 7,997
  • 3
  • 56
  • 43
-3

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

Norman
  • 509
  • 2
  • 4