1

I have a situation where I want to extract a file from nested tar.gz. The structure of .tar.gz is as

  • test.tar.gz
    • data1
      • data2
        • data3
          • test2.tar.gz
            • data4
              • data5
                • test.log

I want to extract only test.log file from the test.tar.gz file. I have seen this post with which we can extract file of tar.gz but not in nested levels.

I am adding output of tar tfz data1.tar.gz The folder structure might be a bit different as entered the above structure manually.


data1/.
data1/META.json
data1/TEMP
data1/TEMP/temp-2
data1/TEMP/temp-2/1-chksum.txt
data1/TEMP/temp-2/1
data1/TEMP/temp-2/1/otherfiles
data1/TEMP/temp-2/1/otherfiles/2016_06_24.tar.gz

So the test.log file is present within a nested folder inside 2016_06_24.tar.gz

  • Can you post the real output of tar tfz test.tar.gz because your "nested" picture doesn't make things too clear. Edit the question with the output. – Stephen Harris Jul 28 '16 at 20:01
  • do I understand your diagram correctly to mean that the data4 directory is a member of the test2.tar.gz archive? – Jeff Schaller Jul 28 '16 at 20:01
6

Assuming that data4 & etc are members of the compressed test2.tar.gz archive, and using GNU tar's --strip-components option:

tar xzOf ./test.tar.gz data1/data2/data3/test2.tar.gz | \
  tar xzf - --strip-components=2 data4/data5/test.log

... which tells the first tar to extract the nested compressed tar file to stdout, then tells the second tar to take that inputted file and extract only the data4/data5/test.log file, stripping the first two components out. That will drop the test.log file in your current directory. If you do not have GNU tar, simply remove the --strip-components option, and the file will be extracted with the path that it was archived with.

  • 1
    The --strip-components=2 I think makes this the better answer. -f - is unnecessary, but I suppose that's just stylistic preference, but I must question your two different CLI switch styles (-x -z -O -f in the first case, xzf in the second) – Dylan Frese Jul 28 '16 at 20:15
  • 1
    You should also probably mention that --strip-components is a feature of GNU tar, and may not be found on all POSIX tar implementations – Dylan Frese Jul 28 '16 at 20:17
  • 1
    The Q was tagged Linux, so I made a bit of an assumption. – Jeff Schaller Jul 28 '16 at 20:22
  • does it have to be -x -z -O -f or does xzOf also work? – immibis Jul 29 '16 at 1:28

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.