从管道在命令行上创建zip时,如何指定zip中的文件名? [英] How do you specify filenames within a zip when creating it on the command line from a pipe?

查看:434
本文介绍了从管道在命令行上创建zip时,如何指定zip中的文件名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从正在通过管道传递的文件内容中创建一个zip文件,例如

I'm trying to create a zip file from file contents which are being piped in, e.g.

mysql [params and query] | zip -q output.zip -

这将正确写入zip,但是当您打开zip时,其中的文件称为-".有什么方法可以指定在zip中应该包含管道输入数据的文件名吗?

This writes the zip correctly, but when you open the zip, the file within it is called "-". Is there any way of specifying what the filename of the piped in data should be within the zip?

推荐答案

据我所知,您无法同时使用zip命令来完成这两项工作,我的意思是您不能同时指定文件名和内容.您可以通过管道传输内容并将生成的文件为-,也可以通过管道将文件名与-@一起使用.

From what i can gather you cannot do both with the zip command, i mean you cannot both specify the filenames and pipe the content. You can either pipe the contents and the resulting file is - or you can pipe the filenames with -@.

这并不意味着使用其他技术是不可能做到的.我概述了以下内容之一.这确实意味着您必须安装PHP并加载zip扩展.

That does not mean that doing so is impossible using other techniques. I outline one of those below. It does mean that you have to have PHP installed and the zip extension loaded.

可能还有很多其他方式可以做到这一点.但这是我所知道的最简单的方法.哦,也是单线的.

There could be a whole bunch of other ways to do it. But this is the easiest that I know of. Oh and it's a one-liner too.

这是一个使用PHP的有效示例

This is a working example using PHP

echo contents | php -r '$z = new ZipArchive();$z->open($argv[1],ZipArchive::CREATE);$z->addFromString($argv[2],file_get_contents("php://stdin"));$z->close();' test.zip testfile

要在Windows上运行,只需交换单引号和双引号.或者只是将脚本放在文件中.

To run on windows just swap single and double quotes. Or just place the script in a file.

"test.zip"是生成的Zip文件,"testfile"是正在通过管道传递到命令中的内容的名称.

"test.zip" is the resulting Zip file, "testfile" is the name of the contents that are being piped into the command.

unzip -l test.zip

Archive:  test.zip
  Length      Date    Time    Name
---------  ---------- -----   ----
        6  01-07-2010 12:56   testfile
---------                     -------
        6                     1 file

这是一个使用python的有效示例

And here is a working example using python

echo contents | python -c "import sys
import zipfile
z = zipfile.ZipFile(sys.argv[1],'w')
z.writestr(sys.argv[2],sys.stdin.read())
z.close()
" test5.zip testfile2

unzip -l

Archive:  test5.zip
  Length     Date   Time    Name
 --------    ----   ----    ----
        9  01-07-10 13:43   testfile2
 --------                   -------
        9                   1 file

unzip -p

contents

这篇关于从管道在命令行上创建zip时,如何指定zip中的文件名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆