Linux 如何创建没有完整目录结构的 zip 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9710482/
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-06 05:11:56  来源:igfitidea点击:

How to create a zip file without entire directory structure

linuxzip

提问by Brandon Yates

I am trying to create a zip file and want to preserve most of the directory structure, but not the rootdir as defined from the command line. The command I'm using is:

我正在尝试创建一个 zip 文件并希望保留大部分目录结构,但不是从命令行定义的 rootdir。我使用的命令是:

zip -r out.zip /foo/bar/

I'd like it to recurse through bar and add all files with preserved directory structure (which it does). However I do not want 'foo' to be the top level directory in the zip file created. I would like bar to be the top level directory.

我希望它通过 bar 递归并添加所有具有保留目录结构的文件(它确实如此)。但是,我不希望 'foo' 成为创建的 zip 文件中的顶级目录。我希望 bar 成为顶级目录。

Is there any easy way to go about this? I realize I could change directories before zipping to avoid the problem, but I'm looking for a solution that doesn't require this.

有什么简单的方法可以解决这个问题吗?我意识到我可以在压缩之前更改目录以避免该问题,但我正在寻找不需要这样做的解决方案。

采纳答案by kbyrd

I don't believe zip has a way to exclude the top level directory. I think your best bet would be to do something like: pushd /foo; zip -r out.zip ./bar; popd;

我不相信 zip 有办法排除顶级目录。我认为你最好的选择是做这样的事情: pushd /foo; zip -r out.zip ./bar; 弹出;

But this is exactly the sort of answer you said you didn't want.

但这正是你说你不想要的那种答案。

回答by Claude Schlesser

This should do it:

这应该这样做:

cd /foo/bar/ 
zip -r ../out.zip *

The archive will be in /foo/out.zip

存档将在 /foo/out.zip

回答by reisio

7za -tzip out.zip -w foo/bar/.

7za -tzip out.zip -w foo/bar/.

回答by Nick

If someone stumbles upon this and is not satisfied with the above solution, here follows a very simple workaround to not zip long subdirectories. It involves temporarily creating a folder in C:/, and after zipping simply deleting it:

如果有人偶然发现这一点并且对上述解决方案不满意,这里遵循一个非常简单的解决方法来不压缩长子目录。它涉及在 C:/ 中临时创建一个文件夹,并在压缩后简单地将其删除:

ZipFiles <- list.files(".../ZipFiles") # Insert your long subdirectory into .../

dir.create("C:/ZipFiles")
dir.create(".../FolderToBeZipped")
file.copy(from = ZipFiles,to = "C:/ZipFiles")
zip(".../FolderToBeZipped",
    files = "C:/ZipFiles")
unlink("C:/ZipFiles",recursive = TRUE)

The result then is .../FolderToBeZipped.zip/ZipFiles/

结果是 .../FolderToBeZipped.zip/ZipFiles/

The benefit is that you need not be within the subdirectory (or project) when executing the code.

好处是您在执行代码时不需要在子目录(或项目)中。