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
How do I exclude absolute paths for tar?
提问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 /path
with 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 tar
use --strip-path
for this operation instead.
该手册页有名单tar
的许多选项,包括这一个。一些早期版本的tar
使用--strip-path
此操作来代替。
回答by Johnny Baloney
You are incorrectly using the -C
switch, 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/path
do:
或者,如果您想打包所有内容,/www/path
请执行以下操作:
tar -cf tarname.tar -C /www/path .
You can use -C
switch 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'
--transform
argument 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
,它将删除所有路径信息,而不仅仅是固定数量的组件。