40

I am running a PHP script that gets me the absolute paths of files I want to tar up. This is the syntax I have:

tar -cf tarname.tar -C /www/path/path/file1.txt /www/path/path2/path3/file2.xls

When I untar it, it creates the absolute path to the files. How do I get just /path with everything under it to show?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Angel S. Moreno
  • 3,469
  • 3
  • 29
  • 40

4 Answers4

53

You are incorrectly using the -C switch, which is used for changing directories. So what you need to do is:

tar -cf tarname.tar -C /www/path path/file1.txt path2/path3/file2.xls

or if you want to package everything under /www/path do:

tar -cf tarname.tar -C /www/path .

You can use -C switch multiple times.

Johnny Baloney
  • 3,409
  • 1
  • 33
  • 37
53

If you want to remove the first n leading components of the file name, you need strip-components. So in your case, on extraction, do

tar xvf tarname.tar --strip-components=2

The man page has a list of tar's many options, including this one. Some earlier versions of tar use --strip-path for this operation instead.

ire_and_curses
  • 68,372
  • 23
  • 116
  • 141
12

For me the following works the best:

tar xvf some.tar --transform 's?.*/??g'

--transform argument is a replacement regex for sed, to which every extracted filepath is fed. Unlike --strip-components, it will remove all path information, not just fixed number of components.

Roman Saveljev
  • 2,544
  • 1
  • 21
  • 20
  • 2
    Note that the long name option `--transform` is for GNU tar only. BSD tar's equivalent option is `-s` following `/old/new/[gps]` pattern, and using this way, as you said it will flatten the directory hierarchy, might not be useful in practice. – Meow Nov 02 '14 at 04:05
  • 1
    Best option when you don't know how deep the rabbit hole goes (I mean, your directory structure). Make sure all file names are unique across directories or you may experience unexpected results. – trs Jul 10 '16 at 20:51
2

If you don't know how many components are in the path, you could try this:

DIR_TO_PACK=/www/path/
cd $DIR_TO_PACK/..
tar -cf tarname.tar $(basename $DIR_TO_PACK)
Andreas Baumgart
  • 2,647
  • 1
  • 25
  • 20