Copy the contents of all search results into a single file. I don't want to copy the search result but the file contents of the search result.

For example my search result returned a list of 10 files then I would like to copy the contents of those 10 files into a single file (e.g dump.test).

1 Answer 1


With GNU grep and xargs:

grep -rlZ search-text some/dir/ | xargs -r0 cat > dump.test

-l is to list the files that contain at least one line matching the search-text. -Z is to print that line NUL-delimited so it can be safely passed to xargs -0.

-r to search in all the files inside some/dir/ recursively.


find some/dir -type f -size +0 -exec grep -q search-text {} \; 
   -exec cat {} + > dump.test

That will be less efficient as that means running one grep command per non-empty file.

  • Shouldent you use the >> to append to the file rather than > which will erase the content each time ?
    – Boogy
    Jun 23, 2014 at 11:31
  • when i try using the following command, I am getting the error:grep -rlz vishal*20140608* | xargs -r0 cat > mydump.test xargs: illegal option -- r xargs: Usage: xargs: [-t] [-p] [-e[eofstr]] [-E eofstr] [-I replstr] [-i[replstr]] [-L #] [-l[#]] [-n # [-x]] [-s size] [cmd [args ...]] grep: illegal option -- r grep: illegal option -- z Usage: grep -hblcnsviw pattern file . . .
    – user73352
    Jun 23, 2014 at 11:49
  • @user73352, as I said, that's for GNU grep and xargs. That won't work with other implementations of grep or xargs. Jun 23, 2014 at 11:59
  • 1
    @Boogy, not sure what you mean. dump.test is open only once and that is made the standard output of xargs in the first one and find in the second. So all the output of those and their children will be included in there, there will not be any erasing/overwriting. Jun 23, 2014 at 12:05

You must log in to answer this question.

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