Extract a Single File from a Tarball
September 27, 2023 —
Gregg Szumowski
Suppose I have a tarball (.tar.gz file) which is large and I only want to extract a specific file from it. If I know the name of the file all I have to do is pass the file’s relative path that it is stored under to the command line.
Here is an example of the error you will get if you pass the incorrect file specification:
$ tar zxvf dirtree-tarball.tar.gz file-7-30003.txt
tar: file-7-30003.txt: Not found in archive
Since I don’t have the full path, I can just search for it:
$ tar tf dirtree-tarball.tar.gz | grep 'file-7-30003.txt'
./dir_2/file-7-30003.txt
Now I can pass the full path and extract the file:
$ tar zxvf dirtree-tarball.tar.gz ./dir_2/file-7-30003.txt
./dir_2/file-7-30003.txt
$ ls
dir_2 dirtree-tarball.tar.gz
$ tree
.
├── dir_2
│ └── file-7-30003.txt
└── dirtree-tarball.tar.gz
1 directory, 2 files
Note that it extracts it to the same directory tree but it will only extract the file(s) specified on the command line.