81

I know that I can use following command to extract a single file to the current working directory (assume I have a tar file named test.tar and a file named testfile1 and testfile2 are inside it):

$tar xvf test.tar testfile1

And I can use -C option to extract files to another directory:

$tar xvf test.tar -C anotherDirectory/

When I incorporate the above two techniques together, I suppose that I can extract a single file to another directory.

$ tar xvf test.tar testfile1 -C anotherDirectory/

But the result is I can only extract the testfile1 to the current working directory, rather than the anotherDirectory.

I want to know how can I extract a single file from tar to a different directory?

Kimvais
  • 38,306
  • 16
  • 108
  • 142
MengT
  • 1,207
  • 2
  • 14
  • 16
  • 18
    not sure why closed, this comes top in google for me when searching how to extract single file from tar, and as per SO FAQ your are at right place when your question covers: `software tools commonly used by programmers` ... I believe `tar` is very commonly used by programmers (like compiler, editor, source control and so on ...) if you really believe not suitable then move to other SO site but don't close as there don't seem to be other questions covering this topic that come top in google from SO. – stefanB Nov 01 '12 at 23:58

1 Answers1

116

The problem is that your arguments are in incorrect order. The single file argument must be last.

E.g.

$ tar xvf test.tar -C anotherDirectory/ testfile1

should do the trick.

PS: You should have asked this question on superuser instead of SO

Kimvais
  • 38,306
  • 16
  • 108
  • 142
  • 26
    If you won't to include the directory names use `--strip-components`, here is an example that extracts as `bin/helm`: `tar xf helm-v2.9.1-linux-amd64.tar.gz --strip-components=1 -C bin/ linux-amd64/helm` – Cameron Taggart Jun 07 '18 at 17:38