Using the code in this answer, I can easily copy a file containing specific text from one folder to another. With the -r option I can also search inside directories recursively.

The result is that now I have a lot of files copied in the destination directory. What if I want to preserve the directory hierarchy while copying the files?

It's a lot like this or this question, but with the added difficulty that I have to search for specific text inside the files.

FWIW, I'm on Ubuntu 14.04 x64

1 Answer 1


If you found that answer, there would be nothing else special.

$ cd /path/to/srcdir
$ grep -lr PATTERN . | tar -T - -cf - | tar -C /path/to/dstdir -xf -

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .