Bash – ‘Tar’ the result of a ‘find’, preserving the directory structure

bashfindpipeshell-scripttar

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

Best Answer

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).

Related Question