174

How can you extract only the target dir and not the complete dir tree?

compress

tar cf /var/www_bak/site.tar /var/www/site

extract

tar xf /var/www/site.tar -C /tmp

This will produce:

/tmp/var/www/site

How is it possible to avoid the whole dir tree to be created when the file is extracted?

What I want it to extract to:

/tmp/site
NReilingh
  • 494
clarkk
  • 2,135

3 Answers3

448

You want to use the --strip-components=NUMBER option of tar:

 --strip-components=NUMBER
       strip NUMBER leading components from file names on extraction

Your command would be:

tar xfz /var/www/site.gz --strip-components=2 -C /tmp
MikeyB
  • 40,079
54

Why not use -C option when creating:

$ tar cf /var/www/site.tar -C /var/www_bak/ site
quanta
  • 52,423
0

When extracting one item from the archive, --strip-components=NUMBER option can be used. However when extracting more than one item, --transform is helpful. E.g.

tar xf archpackage.tar --transform="s,usr/bin,myapp,;s,usr/share/doc/myapp,myapp," usr/bin/myapp  usr/share/doc/myapp/myapp-example-config.toml

Above command will extract both binary and config file to a directory called myapp

balki
  • 163