如何跳过目录结构的开头解压文件?

如何跳过目录结构的开头解压文件?

我使用绝对路径创建了 tar 档案来保存文件。

/home/mydir/dir1/dir2/dir3/file1.dat
/home/mydir/dir1/dir2/dir3/file2.dat
/home/mydir/dir1/dir2/dir3/file3.dat

我想解压这些档案,跳过路径的前导部分/home/mydir/dir1。我的文件应该恢复到具有以下结构的任何目录中:

dir2/dir3/file1.dat
dir2/dir3/file2.dat
dir2/dir3/file3.dat

如何使用 tar 命令或其他方式执行此操作?

答案1

如果您使用 GNU tar,则可以选择在提取时删除一些前导路径成员:

 `--strip-components=number'

    Strip given number of leading components from file names before extraction.

For example, suppose you have archived whole `/usr' hierarchy to a
tar archive named `usr.tar'. Among other files, this archive
contains `usr/include/stdlib.h', which you wish to extract to the
current working directory. To do so, you type:

$ tar -xf usr.tar --strip=2 usr/include/stdlib.h

(来自GNU tar 文档.)

在你的情况下,--strip=3应该申请。

答案2

使用 GNU tar(在非嵌入式 Linux 和 Cygwin 上找到),您可以在将成员添加到存档或使用以下命令提取它们时对路径应用正则表达式替换:--transform选项

tar -xf foo.tar --transform='s!^/home/mydir/dir1/!!'

*BSD 焦油(包括在 OSX 上),有一个类似的选项称为-s.

tar -xf foo.tar -s '!^/home/mydir/dir1/!!'

POSIX 有pax与 BSD tar 具有相同选项的命令。

pax -r <foo.tar -s '!^/home/mydir/dir1/!!'

相关内容