RackNerd Billboard Banner

How to Extract a Single File or Directory From TAR or TAR.GZ

Archiving files with tar is standard practice in Linux and Unix. But what if you only need to pull out one file or folder, not everything? No need to unpack the whole archive. Here’s a quick guide on extracting just what you need from a .tar or .tar.gz file.


1. List Files in the Archive

Before you extract, check the exact path and filename inside the archive. This helps avoid typos and confusion.

For .tar files:

tar -tf archive.tar

For .tar.gz (or .tgz) files:

tar -tzf archive.tar.gz

You’ll see an output like:

dir1/fileA.txt
dir2/fileB.txt
dir3/

2. Extract a Single File

Basic command:

tar -xf archive.tar path/to/file.txt

For gzipped tarballs:

tar -xzf archive.tar.gz path/to/file.txt

Replace path/to/file.txt with the exact path from the list above.

Example:

To extract just dir2/fileB.txt:

tar -xzf archive.tar.gz dir2/fileB.txt

The file will be restored to your current directory, following its original path structure.


3. Extract a Directory

Same idea, just give the directory name (include the /):

tar -xzf archive.tar.gz dir2/

This grabs everything inside dir2 and recreates the folder.


4. Change Extraction Location

To extract somewhere else, add the -C option:

tar -xzf archive.tar.gz dir2/fileB.txt -C /destination/path

5. Common Issues

  • Path must match exactly: Use the output from tar -tf—the archive is case-sensitive.
  • Relative paths: If you extract to another folder, make sure it exists or create it with mkdir -p /destination/path.

Quick Reference

ActionCommand Example
List contentstar -tzf archive.tar.gz
Extract single filetar -xzf archive.tar.gz path/to/file.txt
Extract directorytar -xzf archive.tar.gz path/to/directory/
Extract to another locationtar -xzf archive.tar.gz file.txt -C /other/directory/

That’s it. No need to extract the whole archive just for one file or folder. These commands save you time and disk space. Bookmark this post for the next time you need a surgical extraction from a tarball.

Have questions or tips? Drop a comment below!

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
RackNerd Billboard Banner
© 2025 Computer Everywhere
Your Everyday Guide to the Digital World.
Terms of Service | Privacy Policy
Copy link