How do I untar a directory that I don't know the path to? I only know the directory name.

I know how to untar a single file with a wildcard: tar -xf somefile.tar.gz --wildcards --no-anchored 'index.php'

2 Answers 2


I would just take two passes at it:

$ tar -tf somefile.tar.gz | grep dir-i-am-looking-for | head -1
$ tar -xf somefile.tar.gz ./foo/bar/dir-i-am-looking-for

I don't see a "wildcard include" option in GNU tar.

  • In this case I'd omit the | head -1. Since he even doesen't know the correct path it could be that there are multiple directories with that name within the archive, so give him the chance to verify this.
    – ktf
    Apr 18, 2012 at 16:26
  • Yes. I included it more as a thing to think about, not a requirement. A useful alternative would be | dirname | sort -u Apr 18, 2012 at 17:04

One way using perl:

Content of script.pl:

use warnings;
use strict;
use Archive::Tar;

## Check input arguments.
die qq[perl $0 <tar-file> <directory>\n] unless @ARGV == 2;

my $found_dir;

## Create a Tar object.
my $tar = Archive::Tar->new( shift );

## Get directory to search in the Tar object.
my $dir = quotemeta shift;

for ( $tar->get_files ) { 

    ## Set flag and extract when last entry of the path is a directory with same 
    ## name given as argument
    if ( ! $found_dir &&  $_->is_dir && $_->full_path =~ m|(?i:$dir)/\Z|o ) { 
        $found_dir = 1;
        $tar->extract( $_ );

    ## When set flag (directory already found previously), extract all files after
    ## it in the path.
    if ( $found_dir && $_->full_path =~ m|/(?i:$dir)/.*|o ) { 
        $tar->extract( $_ );

It accepts two arguments, first one the TAR file and second one the directory to extract. Run it like:

perl script.pl test.tar winbuild

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .