Put tar'd files in a subdirectory

I have a directory setup like the following:

folder_x
file.y
file.z

I would like to create a tar file so that when it's extracted the structure will look something like this:

dir_q/folder_x
dir_q/file.y
dir_q/file.z

How could I get this to work by using tar? For reference, the current command that I'm using is:

tar -czf archive.tar.gz file.y file.z folder_x

Solution 1:

I've never used the --transform option, but I gather it would do what you need:

tar -czf archive.tar.gz --transform 's,^,dir_q/,' file.y file.z folder_x

Realize the use of , instead of / as separator, so we can add a trailing slash.

Solution 2:

If you don't mind creating the new directory...

mkdir dir_q;tar -C $_ -xzvf archive.tar.gz

alternatively, make a new directory, untar the file to that directory, then re-tar it from the parent directory to include it's name in the extracted version. That way you do not have to remember some super long invocation.