Commands.page Logo

How to Extract Specific Files from Tar Archive in Ubuntu

Managing compressed archives is a common task in Ubuntu, but extracting an entire bundle is often unnecessary when you only need a few items. This guide explains how to use the tar command to selectively extract specific files or directories from a tarball without unpacking everything. You will learn the exact syntax and options required to retrieve only the data you need efficiently.

To extract only specific files from a tar archive, use the tar command followed by the extract flag, the archive name, and the specific file paths you wish to retrieve. The basic syntax requires the -x flag for extraction, the -f flag to specify the file, and the name of the target file at the end of the command.

Basic Command Syntax

The standard command structure looks like this:

tar -xf archive.tar filename

In this example, -x tells tar to extract, -f specifies the archive file name, and filename is the specific file you want to pull out. You can list multiple files separated by spaces to extract several items at once.

Using Verbose Mode

Adding the -v flag provides verbose output, showing you exactly which files are being extracted in the terminal. This is helpful for confirming the operation succeeded.

tar -xvf archive.tar filename

Extracting to a Specific Directory

If you want to extract the specific file into a directory other than the current working folder, use the -C option followed by the destination path.

tar -xf archive.tar filename -C /path/to/destination

Using Wildcards

You can also use wildcards to extract groups of files matching a pattern. For example, to extract all log files ending in .log, use the following command. Note that wildcards often require quotes to prevent the shell from expanding them prematurely.

tar -xf archive.tar '*.log'

Listing Files Before Extraction

Before extracting, it is wise to verify the exact path of the file inside the archive. Use the -t flag to list the contents without extracting them.

tar -tf archive.tar

Once you know the precise path listed in the output, use that exact path in your extraction command to ensure success.