How do I exclude absolute paths for tar?

我是研究僧i 提交于 2019-12-20 10:32:05

问题


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:

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?


回答1:


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

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

The man page has a list of tar's many options, including this one. Some earlier versions of tar use --strip-path for this operation instead.




回答2:


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

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:

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

You can use -C switch multiple times.




回答3:


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.




回答4:


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)


来源:https://stackoverflow.com/questions/3153683/how-do-i-exclude-absolute-paths-for-tar

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!