views:

1951

answers:

2

How to I extract a subdirectory in a tarball into the current directory?

Example, the tarball from wordpress:

wordpress/
wordpress/wp-trackback.php
wordpress/wp-config-sample.php
wordpress/wp-settings.php
wordpress/wp-rss2.php
wordpress/readme.html
wordpress/index.php
...

How do I extract everything under wordpress/ into the current directory? In otherwords, it will not create a wordpress directory.

I've tried this with no luck:

tar xvfz latest.tar.gz wordpress -C ./

I know I can extract it normally and move it back, but I figure there has to be a way to do it in one shot.

+5  A: 

Why don't you untar normally, then just:

mv wordpress/.* .
mv wordpress/* .
rmdir wordpress

But alas, there's:

tar --strip-components=1 -zxvf wordpress.tgz
kch
I was hoping there was a way to do it in one command.
Cory R. King
Interestingly, strip components is an option for my FreeBSD boxen, but not for some of my older linux installs.
Cory R. King
+1. Note that, if the tarfile contains a file or directory named wordpress/wordpress, your second mv command will fail. (But kudos for catching the hidden file case.)
j_random_hacker
A: 

Surprisingly, my tar (GNU tar v1.16) doesn't have an option to strip initial pathname elements.

However, it seems that more recent versions sport a --strip-components=number parameter, which will strip that many compononents from the start of the path.

If like me you are using an older tar, and you are certain that the archive does not contain a directory or file named wordpress/wordpress, you could always just make a symlink from wordpress to ., then extract as usual:

ln -s . wordpress
tar xvfz latest.tar.gz wordpress
rm wordpress
j_random_hacker
The box I'm on doesn't have that "strip-components" param, so the symlink idea is an interesting one. I can't help but to wonder if there is something we are missing though. Unix is like that... there is usually some non-obvious way that you can only learn by asking. Hence my question!
Cory R. King
@Cory: Well I think the answer to that is "The tar developers realised, and introduced the --strip-components option." :)
j_random_hacker