Rename Directory Name Before tar Happens

BashShellCommand LineTar

Bash Problem Overview


I have a directory e.g. /var/tmp/my-dir/ that I frequently compress with the following command:

$ cd /var/tmp/
$ tar -zcf my-dir.tar.gz my-dir/*

Later, when I untar my-dir.tar.gz, it'll create my-dir/ in the current directory. It sounds like the my-dir directory is "wrapped" inside the tarball. Is there a tar option to rename my-dir to e.g. your-dir before the actual tarring happens. So that ...

$ tar -zxf my-dir.tar.gz
# So that ... this creates your-dir/, instead of my-dir/

Thanks.

Bash Solutions


Solution 1 - Bash

Which tar?

GNU Tar accepts a --transform argument, to which you give a sed expression to manipulate filenames.

For example, to rename during unpacking:

tar -zxf my-dir.tar.gz --transform s/my-dir/your-dir/

BSD tar and S tar similarly have an -s argument, taking a simple /old/new/ (not a general sed expression).

Solution 2 - Bash

For mac works -s flag.

Rename on compress:

tar -zcf my-dir.tar.gz -s /^my-dir/your-dir/ my-dir/*

Rename on extract:

tar -zxf my-dir.tar.gz -s /^my-dir/your-dir/

Solution 3 - Bash

Late to to the party but here's my time-proven approach to this. When I have a tar file that extracts to a top level directory name I don't like, I solve it by creating the directory name I do like and then using tar with the -C and --strip-component options.

mkdir your-dir && tar -zxvf my-dir.tar.gz -C your-dir --strip-components=1

The -C extracts as if in the directory you specify while the --strip-component says to ignore the first level stored in the tarfile's contents.

At first glance this approach is perhaps less elegant than the sed-style solution given by others, but I think this way does have some merit.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmoeyView Question on Stackoverflow
Solution 1 - BashephemientView Answer on Stackoverflow
Solution 2 - BashDamneDView Answer on Stackoverflow
Solution 3 - BashSO StinksView Answer on Stackoverflow