I'm looking for a pattern in files using find, then I only want the first ten I find and tar those.

find /var/log/file | xargs grep "pattern" | head -n10​ | tar -czvf tarfile.tgz

I have also tried to xargs the tar. This too results in errors. What am I doing wrong?

Here is what I see from the first command:

tar: Cowardly refusing to create an empty archive
Try `tar --help' or `tar --usage' for more information.

You can use

tar cvzf files.tar.gz $(find /var/log/file -type f -exec grep -l "pattern" {} + | \
head -n10)

here, grep -l will print only files which matches pattern.

You would have to use -P option of tar if you are getting error like

error tar: Removing leading `/' from member names

see man tar

-P, --absolute-names
     don't strip leading '/'s from file names

Or you may specify -C to change the directory, instead of specifying full path of the archive file.

  • This works. Just tested it and it created the tar. Although I did get the error tar: Removing leading `/' from member names – user53029 Sep 2 '16 at 6:36
  • Removing leading `/' from member names – user53029 Sep 2 '16 at 6:37
  • What if I wanted to get all files found that matched pattern not just the first 10. How would I then terminate the end of the command properly? use only -exec grep -l pattern {} + or {} \; – user53029 Sep 2 '16 at 6:51
  • 1
    you would have to use -exec grep -l pattern {} \; – Rahul Sep 2 '16 at 7:01
  • And the closing brace? Place it right next to the {} \; or leave a space or does it matter? – user53029 Sep 2 '16 at 7:03


tar cvzf tarfile.tgz $(find /var/log/file | grep "pattern" | head -n10 )


  • code inside $( ) build a list of 10 files.

unlike cpio, tar will not accept a list of file in stdin.

  • Would there be a problem if the path included wildcards? I am still getting the same error. my actual path looks more like this -- find /var/log/*/*/file. Thats the only thing I can think of that would cause this problem – user53029 Sep 2 '16 at 6:29
  • Actually I just used the exact path to rule out a wilcard issue and still getting the same error. – user53029 Sep 2 '16 at 6:32
  • you shouldn't mix * and find, try find /var/log -type f -name file – Archemar Sep 2 '16 at 6:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.