Unix / Linux: Extract Tar File with Absolute Path

Unix / Linux: Extract Tar File with Absolute Path

Objective: Extract a tar file with absolute path to a relative or different path. For example, if a tar arahive contains the file /etc/hosts, it has to be extracted to /home/user/etc/hosts instead.

Let’s say that you have the following tar archive that stores a file – /etc/hosts. This file has an absolute path as it has a leading slash ‘/‘.

$ tar tvf foo.tar
-rw-r--r-- root/root      1615 2016-05-18 21:59 /etc/hosts

We do not want our original /etc/hosts file to be overwritten when we extract this tar archive. To extract the file to a relative path, we can use the -C option to specify the target or relative directory. This is supported on GNU tar.

$ mkdir out

$ tar xvf rtar-linux.tar -C out
/etc/passwd

$ find out
out
out/etc
out/etc/hosts

As you can see from above, we created a directory called out and instructed tar to extract the contents to the out directory. Once the tar archive has been extracted, we can see that the /etc/hosts file is in the out directory.

If your tar program does not support the -C option, you can consider using pax. The -s option of pax can be used to modify filenames using regular expressions, based on sed. The format is: -s /old/new/ [gp]

The optional trailing g is as defined in the sed command. The optional trailing p causes successful substitutions to be written to standard error.

To extract to a relative path using pax, use the following syntax.

$  pax -r -s '!^/!out/!p' < foo.tar
/etc/hosts >> out/etc/hosts

$ find out
out
out/etc
out/etc/hosts

The regular expression that we passed to pax is to match a “/” at the beginning and replace it with “out/”.

This can also be achieved by using chroot but it’s a bit more troublesome.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值