16

I am running this command to find all my files that contain (with help of regex)"someStrings" in a tree directory.

grep -lir '^beginString' ./ -exec cp -r {} /home/user/DestinationFolder \; 

It found files like this:

FOLDER
a.txt
-->SUBFOLDER
  a.txt
---->SUBFOLDER
     a.txt

I want to copy all files and folder, with the same schema, to the destination folder, but i don't know how to do it. It's important copy files and folder, because several files found has the same name and I need to keep it.

jww
  • 97,681
  • 90
  • 411
  • 885
user6372336
  • 163
  • 1
  • 1
  • 4

1 Answers1

25

Try this:

find . -type f -exec grep -q '^beginString' {} \; -exec cp -t /home/user/DestinationFolder {} +

or

grep -lir '^beginString' . | xargs cp -t /home/user/DestinationFolder

But if you want to keep directory structure, you could:

grep -lir '^beginString' . | tar -T - -c | tar -xpC /home/user/DestinationFolder

or if like myself, you prefer to be sure about kind of file you store (only file, no symlinks), you could:

find . -type f -exec grep -l '^beginString' {} + | tar -T - -c |
    tar -xpC /home/user/DestinationFolder

and if your files names could countain spaces and/or special characters, use null terminated strings for passing grep -l output (arg -Z) to tar -T (arg --null -T):

grep -Zlir '^beginString' . | xargs --null cp -t /home/user/DestinationFolder

or

find . -type f -exec grep -lZ '^beginString' {} + | tar --null  -T - -c |
    tar -xpC /home/user/DestinationFolder
F. Hauri - Give Up GitHub
  • 64,122
  • 17
  • 116
  • 137
  • awesome, it works!!! I don't kwon how do it but works! The command make some backup files, I deleted it manually and fine. Thanks my friend!!! You saved my life – user6372336 May 23 '16 at 18:11
  • Nice encyclopedia of rare parameters, thanks for sharing :-) – Jarek May 17 '22 at 17:59