Extract without First Directory

by Mark Sanborn on January 6, 2009

Whenever I download something that is compressed on the Internet in a .zip, .rar or .tar.gz it is always a crapshot whether or not it contains a “container directory”. A “container directory” is a directory that contains all the other files usually with the same name as the compressed file.

For example the Zend Framework when downloaded contains a folder called, ‘ZendFramework-1.7.2‘. All the other files are contained under this folder. This is great but sometimes I want to extract the contents of the folder without the “container folder”.

This is how I used to extract the contents and remove the “container folder”:

tar -xvf ZendFramework-1.7.2.tar.gz

Get rid of the tarball…

rm ZendFramework-1.7.2.tar.gz

cd ZendFramework-1.7.2/

Which would result in:

Zend Framework Directory Structure

Copy everything in the “container” folder and move it up a directory.

cp -rf * ../

Now I have found a better way…

A better way

 
The flag that I have learned is the strip flag. This will strip off the first directory and extract the rest.

tar -xvf ZendFramework-1.7.2.tar.gz --strip 1

The only thing now is… How do I tell if a tar contains a “container folder”?

Easy

tar -tf ZendFramework-1.7.2.tar.gz | head

This will list contents of the file ‘ZendFramework-1.7.2.tar.gz‘ showing only the first few lines.

What do you think? Is there an even better way?

5 comments

Mark, thanks a lot for the tip! This always bothered me.

by Srikanth on January 6, 2009 at 8:36 am #

Very useful. I wonder though what it will do if, say, you have a README file in the root of the tar and THEN a head directory. Will it just merge all of them into the root? Will it just not extract the README? You should find out :D

by Jade Robbins on January 6, 2009 at 9:21 am #

It will ignore the readme, which is why you need to use, tar -tf blah.tar.gz | head

by Mark Sanborn on January 6, 2009 at 9:22 am #

Finally I’ve found what I was looking for!

Maybe there’s a way to automatically detect if there’s a container folder since it seems the container folder often shares the same name as the .tar.gz file without the extension?

by Matt on January 14, 2009 at 11:02 pm #

This is GENIUS! Seriously how do you come up with these ideas?!?!?! LOVE IT

by Jade Robbins on January 25, 2009 at 3:15 am #