Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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'

share|improve this question

2 Answers 2

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( $_ );
        next;
    }   

    ## 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
share|improve this answer

I would just take two passes at it:

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

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

share|improve this answer
    
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 '12 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 –  Warren Young Apr 18 '12 at 17:04

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.