Home » Linux » Bash: find and copy

Bash: find and copy

Posted by: admin November 30, 2017 Leave a comment

Questions:

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

Answers:

I would recommend using find‘s -exec option:

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

As always, consult the manpage for best results.

Questions:
Answers:

I usually use this one:

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

Questions:
Answers:

If your cp is GNU’s:

find . -ctime 15 -print0 | xargs -0 cp --target-directory=../otherfolder

Questions:
Answers:

You can do it with xargs:

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

See also grep utility in shell script.

Questions:
Answers:

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;

Questions:
Answers:

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