9

I want to tar some files (and directories) but want to create an additional directory those files should reside in.

So for example for the following directory structure:

myproject
  + file1
  + file2
  + subdir1
    + file3

I cd into the myproject directory and want to create the tar archive

tar czf myproject.tgz --place-into-dir myproject-1.0 file2 subdir1

to receive a tar archive with the following content:

myproject-1.0
  + file2
  + subdir1
    + file3

I am searching for an option like my fictional "--place-into-dir" above. So the files should not be placed directly into the archive, but instead into an additional directory that is only created in the tar archive.

I want to avoid first creating that directory, copying all the files to that directory and then deleting them again only to create the tar archive.

radlan
  • 2,393
  • 4
  • 33
  • 53
  • Are you using `GNU tar`? Check output of `tar --version`? – Inian Dec 06 '16 at 07:59
  • @Inian Yes, it is GNU tar. Therefore the solution from kalj and Anton with `--transform` works. Thanks – radlan Dec 06 '16 at 15:26
  • @Inian I didn't try it, but your example doesn't do what I want. See the the answers of kalj and Anton. – radlan Dec 06 '16 at 16:42
  • Is there a solution when using bsdtar on a Mac? `$ tar --version` yields `bsdtar 2.8.3 - libarchive 2.8.3`. `tar --help` doesn't yield anything obvious, so probably not. – Troy Daniels Jan 23 '20 at 15:18

2 Answers2

14

You can create a directory on the fly inside the archive using --transform:

tar czf myproject.tgz --transform 's,^,myproject-1.0/,' file2 subdir1
kalj
  • 1,432
  • 2
  • 13
  • 30
5

GNU tar has --transform option:

--transform=EXPRESSION, --xform=EXPRESSION

use sed replace EXPRESSION to transform file names

This should help you:

tar --transform 's/^myproject$/\0-1.0/' -czf myproject.tgz myproject
Community
  • 1
  • 1
Anton N. Petrov
  • 576
  • 4
  • 10