Extract specific folder from tarball into specific folder

Solution 1:

Tl;dr

Since you are in /tmp already, you can just discard the -C option (since by default tar will extract files in the current working directory) and just add --strip-components=2:

tar --strip-components=2 -xfvz archive.tar.gz folder/in/archive

GNU tar by default stores relative paths.

Whether an archive uses relative paths can be checked by running tar -tf archive | head -n 1, which will print the path of the first file in the archive; if that file's path is a relative path, all the files in the archive use relative paths:

% tar -tf bash-4.3.tar.gz | head -n 1
bash-4.3/

To extract a single file / folder from an archive that uses relative paths without its ancestors into a relative path you'll need two options: -C and --strip-components=N: in the example below the archive bash-4.3.tar.gz uses relative paths and contains a file bash-4.3/doc/bash.html which is extracted into a relative path path (-C specifies the directory in which to extract the files, --strip-components=2 specifies that the parent and the parent of the parent of the extracted files should be ignored, so in this case only bash.html will be extracted into the target directory):

% tree
.
├── bash-4.3.tar.gz
└── path

1 directory, 1 file
% tar -tf bash-4.3.tar.gz | grep -F 'bash.html'
bash-4.3/doc/bash.html
% tar -C path --strip-components=2 -zxf bash-4.3.tar.gz bash-4.3/doc/bash.html
% tree
.
├── bash-4.3.tar.gz
└── path
    └── bash.html

1 directory, 2 files

So, back to your command, since you are in /tmp already, you can just discard the -C option (since by default tar will extract files in the current working directory) and just add --strip-components=2:

tar --strip-components=2 -xfvz archive.tar.gz folder/in/archive

Solution 2:

tar stores relative paths

If you need to extract a particular folder, have a look at what's in the tar file:

tar -tvf archive.tar.gz

And note the exact filename. tar -xvf foo.tar folder/in/archive
# Note: no leading slash