Linux 如何排除 tar 的绝对路径?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3153683/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 20:11:45  来源:igfitidea点击:

How do I exclude absolute paths for tar?

linuxbashtar

提问by Angel S. Moreno

I am running a PHP script that gets me the absolute paths of files I want to tar up. This is the syntax I have:

我正在运行一个 PHP 脚本,它可以获取我想要压缩的文件的绝对路径。这是我的语法:

tar -cf tarname.tar -C /www/path/path/file1.txt /www/path/path2/path3/file2.xls

When I untar it, it creates the absolute path to the files. How do I get just /pathwith everything under it to show?

当我解压它时,它会创建文件的绝对路径。我如何/path才能显示它下面的所有内容?

采纳答案by ire_and_curses

If you want to remove the first n leading components of the file name, you need strip-components. So in your case, on extraction, do

如果要删除文件名的前 n 个前导组件,则需要strip-components. 所以在你的情况下,在提取时,做

tar xvf tarname.tar --strip-components=2

The man pagehas a list of tar's many options, including this one. Some earlier versions of taruse --strip-pathfor this operation instead.

手册页有名单tar的许多选项,包括这一个。一些早期版本的tar使用--strip-path此操作来代替。

回答by Johnny Baloney

You are incorrectly using the -Cswitch, which is used for changing directories. So what you need to do is:

您错误地使用了-C用于更改目录的开关。所以你需要做的是:

tar -cf tarname.tar -C /www/path path/file1.txt path2/path3/file2.xls

or if you want to package everything under /www/pathdo:

或者,如果您想打包所有内容,/www/path请执行以下操作:

tar -cf tarname.tar -C /www/path .

You can use -Cswitch multiple times.

您可以-C多次使用switch。

回答by Andreas Baumgart

If you don't know how many components are in the path, you could try this:

如果你不知道路径中有多少个组件,你可以试试这个:

DIR_TO_PACK=/www/path/
cd $DIR_TO_PACK/..
tar -cf tarname.tar $(basename $DIR_TO_PACK)

回答by Roman Saveljev

For me the following works the best:

对我来说,以下效果最好:

tar xvf some.tar --transform 's?.*/??g'

--transformargument is a replacement regex for sed, to which every extracted filepath is fed. Unlike --strip-components, it will remove all path information, not just fixed number of components.

--transform参数是 sed 的替换正则表达式,每个提取的文件路径都被提供给它。与 不同--strip-components,它将删除所有路径信息,而不仅仅是固定数量的组件。