8

I want to tar all the *.txt files that I get as the result of a find command, that exist in a directory having a tree structure like this:

  • Directory_name
    • dir1
      • file1.pdf
      • file1.txt
    • dir2
      • file2.pdf
      • file2.txt
    • dir3
      • file3.pdf
      • file3.txt

(the filenames are just examples).

But I want to preserve the directory structure.

What command can give me a tar.gz file with this content?

  • dir1
    • file1.txt
  • dir2
    • file2.txt
  • dir3
    • file3.txt

1 Answer 1

12

You can use xargs to feed the output of a command as arguments to another:

find . -iname '*.txt' -print0 | xargs -0 tar zcvf the_tarball.tar.gz 

Note here the -print0 from find and -0 from xargs work in conjunction to delimit file names correctly (so that names with spaces and such aren't a problem).

2
  • 8
    xargs is not even necessary, you can pipe the output of find directly to tar via stdin. For your example: find . -iname '*.txt' | tar zcvf the_tarball.tar.gz --files-from - Explained here: stackoverflow.com/a/9534272/4017010 and the general topic was already discussed here: unix.stackexchange.com/questions/5641/… Commented Nov 28, 2014 at 21:28
  • Hi, this worked perfectly. And thanks doktor5000 for the precision :) Commented Dec 1, 2014 at 9:48

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.