linux - 如何抑制 tar 归档文件中的目录名称?

标签 linux unix tar

假设我有以下目录和文件

inc:
inc/foo.h
inc/bar.h
inc/more.h
src:
src/foo.cc
src/bar.cc
src/more.cc

我想使用 tar 生成一个磁带存档,其中包含其中一些文件(名称中都带有 foobar) ,但好像它们都在一个目录中。因此,在通过 tar -xf archive.tar 将我的存档解压缩后,我得到了

somewhere/foo.h
somewhere/bar.h
somewhere/foo.cc
somewhere/bar.cc

我可以只使用 tar 而不移动/复制我的文件吗?怎么办?

最佳答案

使用 GNU tartar --help:

File name transformations:

  • --strip-components=NUMBER
    strip NUMBER leading components from file names on extraction

  • --transform=EXPRESSION, --xform=EXPRESSION
    use sed replace EXPRESSION to transform file names

因此,从表面上看,您在提取时使用它:

tar -xf filename.tar --strip-components=1 -C somewhere

-C somewhere 在提取文件之前将目录更改为 somewhere


由于您知道 --strip-components 选项但它不符合您的要求,下一个要尝试的选项是 --transform。由于您要删除路径的所有前导组件,因此表达式可以非常简单:

tar -cf filename.tar --transform='s%.*/%%' .

这似乎可行;我使用以下方法对其进行了测试:

$ mkdir junk
$ cd junk
$ mkdir inc src
$ for file in inc/foo.h inc/bar.h inc/more.h src/foo.cc src/bar.cc more.cc; do cp ../makefile $file; done
$ tar -cf - --transform='s%.*/%%' . | tar -tvf -
drwxr-x--- jleffler/eng      0 2014-05-06 10:00 ./
-rw-r----- jleffler/eng   1183 2014-05-06 10:00 more.cc
drwxr-x--- jleffler/eng      0 2014-05-06 10:00 inc/
-rw-r----- jleffler/eng   1183 2014-05-06 10:00 more.h
-rw-r----- jleffler/eng   1183 2014-05-06 10:00 bar.h
-rw-r----- jleffler/eng   1183 2014-05-06 10:00 foo.h
drwxr-x--- jleffler/eng      0 2014-05-06 10:00 src/
-rw-r----- jleffler/eng   1183 2014-05-06 10:00 bar.cc
-rw-r----- jleffler/eng   1183 2014-05-06 10:00 foo.cc
$

关于linux - 如何抑制 tar 归档文件中的目录名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23500347/

相关文章:

php - 数据未从 Python 传递到 PHP

linux - 解压tar tar.bz2 文件报错

python - 如何在不包含父目录的情况下在 Python/tar 中创建 tar.gz 存档?

linux - 使用 libtool 更改共享库的名称

linux - pthread 互斥体解锁如何工作?线程是否同时出现?

python - 在服务器上运行 python 脚本

linux - 检查用户输入的格式是否正确

python - 从 python 代码执行 Unix 命令

python - Python 备份脚本

linux - 如何指定 tar 最终结构