Can I extract a specific folder using tar to another folder?

Solution 1:

What you're looking for is the -C option:

$ man tar
<snip>

-C, --directory DIR
       change to directory DIR

Usage, per your example:

$ tar xvzf archivename.tar.gz -C /tmp/testdir/ sampledir/

Also, you may be interested to know that modern versions of tar don't require the z flag to decompress gzipped files; they'll notice it's a .gz and Do The Right Thing automatically.

Solution 2:

You don't need to play crazy games with untarring everything. Tar fully supports only extracting a subset of the files in an archive, as shown in the following (trivial) example:

/tmp $ mkdir tarsrc
/tmp $ cd tarsrc
/tmp/tarsrc $ mkdir a b
/tmp/tarsrc $ touch a/aaa b/bbb
/tmp/tarsrc $ tar cf ../tartest.tar .
/tmp/tarsrc $ cd ..
/tmp $ mkdir tardest
/tmp $ cd tardest
/tmp/tardest $ tar xf ../tartest.tar ./a    
/tmp/tardest $ ls -R
.:
a/

./a:
aaa

The trick is that the pathspec must match the contents of the tarfile exactly. So when you do a tar tf, if the path starts with ./, you've got to put that in, and if it doesn't have it, you have to leave it out. Also, if you want to extract a sub-sub-sub-sub-sub-sub-sub-path, it'll end up N levels deep in the filesystem when you're done.