Skip to content

Instantly share code, notes, and snippets.

@zhiguangwang
Last active January 17, 2024 14:43
Show Gist options
  • Save zhiguangwang/b9059946e181cca81b3e9399c2ea24f9 to your computer and use it in GitHub Desktop.
Save zhiguangwang/b9059946e181cca81b3e9399c2ea24f9 to your computer and use it in GitHub Desktop.
Rename top-level folder while creating a tar.gz file.
tar czfv NEW_NAME.tar.gz OLD_NAME --transform s/OLD_NAME/NEW_NAME/

Note: this only works with GNU Tar.

Example

we want to tar /opt/zlib/1.2.11 into zlib-1.2.11.tar.gz, and we want the top-level folder inside that tar.gz file to be zlib-1.2.11, not 1.2.11:

$ cd /opt/zlib
$ ls -l
total 4
drwxr-xr-x 5 root root 4096 Mar 12 02:34 1.2.11
$ tar czfv zlib-1.2.11.tar.gz 1.2.11 --transform s/1.2.11/zlib-1.2.11/
1.2.11/
1.2.11/include/
1.2.11/include/zlib.h
1.2.11/include/zconf.h
1.2.11/lib/
1.2.11/lib/pkgconfig/
1.2.11/lib/pkgconfig/zlib.pc
1.2.11/lib/libz.a
1.2.11/share/
1.2.11/share/man/
1.2.11/share/man/man3/
1.2.11/share/man/man3/zlib.3
$ ls -l
total 104
drwxr-xr-x 5 root root  4096 Mar 12 02:34 1.2.11
-rw-r--r-- 1 root root 99144 Mar 13 06:21 zlib-1.2.11.tar.gz
$ tar zxvf zlib-1.2.11.tar.gz
zlib-1.2.11/
zlib-1.2.11/include/
zlib-1.2.11/include/zlib.h
zlib-1.2.11/include/zconf.h
zlib-1.2.11/lib/
zlib-1.2.11/lib/pkgconfig/
zlib-1.2.11/lib/pkgconfig/zlib.pc
zlib-1.2.11/lib/libz.a
zlib-1.2.11/share/
zlib-1.2.11/share/man/
zlib-1.2.11/share/man/man3/
zlib-1.2.11/share/man/man3/zlib.3
$ ls -l
total 108
drwxr-xr-x 5 root root  4096 Mar 12 02:34 1.2.11
drwxr-xr-x 5 root root  4096 Mar 12 02:34 zlib-1.2.11
-rw-r--r-- 1 root root 99144 Mar 13 06:21 zlib-1.2.11.tar.gz
$ tree
.
|-- 1.2.11
|   |-- include
|   |   |-- zconf.h
|   |   `-- zlib.h
|   |-- lib
|   |   |-- libz.a
|   |   `-- pkgconfig
|   |       `-- zlib.pc
|   `-- share
|       `-- man
|           `-- man3
|               `-- zlib.3
|-- zlib-1.2.11
|   |-- include
|   |   |-- zconf.h
|   |   `-- zlib.h
|   |-- lib
|   |   |-- libz.a
|   |   `-- pkgconfig
|   |       `-- zlib.pc
|   `-- share
|       `-- man
|           `-- man3
|               `-- zlib.3
`-- zlib-1.2.11.tar.gz

14 directories, 11 files
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment