How to extract specific file(s) from tar.gz

You can also use tar -zxvf <tar filename> <file you want to extract>

You must write the file name exacty as tar ztf test.tar.gz shows it. If it says e.g. ./extract11, or some/bunch/of/dirs/extract11, that's what you have to give (and the file will show up under exactly that name, needed directories are created automatically).

  • -x: instructs tar to extract files.
  • -f: specifies filename / tarball name.
  • -v: Verbose (show progress while extracting files).
  • -z: filter archive through gzip, use to decompress .gz files.

Let's assume you have a tarball called lotsofdata.tar.gz and you just know there is one file in there you want but all you can remember is that its name contains the word contract. You have two options:

Either use tar and grep to list the contents of your tarball so you can find out the full path and name of any files that match the part you know, and then use tar to extract that one file now you know its exact details, or you can use two little known switches to just extract all files that match what little you do know of your file name—you don't need to know the full name or any part of its path for this option. The details are:

Option 1

$ tar -tzf lotsofdata.tar.gz | grep contract

This will list the details of all files whose names contain your known part. Then you extract what you want using:

$ tar -xzf lotsofdata.tar.gz <full path and filename from your list above>

You may need ./ in front of your path for it to work.

Option 2

$ tar -xzf lotsofdata.tar.gz --wildcards --no-anchored '*contract*'

Up to you which you find easier or most useful.


I was trying to extract a couple hundred files from a tarball with thousands of files the other day. The files I need cannot be referenced by a single wildcard. So I googled and found this page.

However, none of tricks above seem good for my task. I ended up reading the man, and found this option --files-from, so my final solution is

gunzip < thousands.tar.gz | tar -x -v --files-from hundreds.list -f -

and it works like a charm.

Update: The list file should have the same format as you would see from tar -tvf, otherwise you would not be able to extract any files.

Tags:

Tar