How to Tar Specific File Types (Extensions) in a Directory

Tar is a popular archiving utility present in almost all Linux operating system distributions hence removing the need to search and install it from your OS package manager.

The term TAR is an abbreviation for Tape Archive files. If you have been around the Linux OS ecosystem for a while then you should also be familiar with tar’s alternate reference tarball.

When you come across a document with a TAR file format, it simply implies that this single file is a storage location for multiple files or in special circumstances a single file.

Problem Statement

Consider the following random set of different file types existing within a Linux directory.

List Files in Directory
List Files in the Directory

As per the screen capture above, we have a combined set of text files with an .txt extension and image files with an .jpeg extension. Our dilemma is how to use the tar command to only archive the text files or the image files.

Tar Command Usage Examples

If we were to archive the above directory (LinuxShellTips_Files) and all its files (regardless of the file types), the tar command to use would look like the following:

$ tar -czvf final_file.tar.gz /home/dnyce/LinuxShellTips_Files/

In the above command, final_file (with the .tar.gz file extension) is the name of the tar file that will hold the contents of the LinuxShellTips_Files directory.

The tar command options:

  • -c – initiates the creation of the final_file.tar.gz archive.
  • -z – uses gzip to filter the archive.
  • -v – verbose output.
  • -f – makes the .tar.gz file usable.

Tar Files By File Extension

To only tar the text files, we will modify the above command in the following manner:

$ tar -czvf final_file.tar.gz /home/dnyce/LinuxShellTips_Files/*.txt
Tar Files By Extension
Tar Files By Extension

To only tar the jpeg image files, we will modify the tar command as follows:

$ tar -czvf final_images_file.tar.gz /home/dnyce/LinuxShellTips_Files/*.jpeg

Extract Tar Archive Files

To confirm tar actually worked, let us extract our archived files. The -C an option is for navigating to the directory of extraction, -x for extraction.

$ tar -xzvft final_file.tar.gz -C /home/dnyce/LinuxShellTips_Files/texts
$ tar -xzvf final_images_file.tar.gz -C /home/dnyce/LinuxShellTips_Files/images
Extract Tar Files in Linux
Extract Tar Files in Linux

Extracting the tar file lists its content. In this case, one has the text files, and the other one the image files.

We can now comfortably tar specific file types in a directory in Linux.

Got something to say? Join the discussion.

Have a question or suggestion? Please leave a comment to start the discussion. Please keep in mind that all comments are moderated and your email address will NOT be published.