26

我正在尝试从正在输入的文件内容创建一个 zip 文件,例如

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

这会正确写入 zip,但是当您打开 zip 时,其中的文件称为“-”。有什么方法可以指定 zip 中管道数据的文件名应该是什么?

4

6 回答 6

13

你可以这样做。

ls | zip test.zip -@

这是根据我在目录中有 3 个文件的概念来完成的。

-rw-rw-r-- 1 xxx domain users   6 Jan  7 11:41 test1.txt
-rw-rw-r-- 1 xxx domain users   6 Jan  7 11:41 test2.txt
-rw-rw-r-- 1 xxx domain users   6 Jan  7 11:41 test3.txt

和文件本身,结果是

Archive:  test.zip
  Length     Date   Time    Name
 --------    ----   ----    ----
        6  01-07-10 11:41   test1.txt
        6  01-07-10 11:41   test2.txt
        6  01-07-10 11:41   test3.txt
 --------                   -------
       18                   3 files

从 Linux Zip Man 页面

如果文件列表指定为 -@,则 zip 从标准输入中获取输入文件列表。

于 2010-01-07T10:44:33.210 回答
13

您可以使用命名管道,并将请求输出发送给它,同时从它压缩。

mkfifo output.txt ; mysql [params and query] > output.txt & zip output.zip -FI output.txt ; rm output.txt
于 2010-01-07T12:19:54.890 回答
8

我无法处理PHP 答案(更大的 mysql 转储内存不足),并且 FIFO 没有按我的意愿工作,所以我的解决方案是在运行转储后重命名 ZIP 存档中的文件,使用 zipnote(包含在 Debian 上的 zip 包中)。

mysql [params and query] | zip -q output.zip -
echo -e "@ -\n@=newname.sql" | zipnote -w output.zip
于 2016-12-21T12:45:07.230 回答
5

据我所知,你不能同时使用zip命令,我的意思是你不能同时指定文件名和管道内容。您可以通过管道传输内容和生成的文件,也-可以使用管道传输文件名-@

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

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

这是一个使用 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 上运行,只需交换单引号和双引号。或者只是将脚本放在一个文件中。

“test.zip”是生成的 Zip 文件,“testfile”是通过管道传输到命令中的内容的名称。

结果来自unzip -l test.zip

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

这是一个使用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
于 2010-01-07T11:56:12.707 回答
2
mysql [params and query] | python3 -c "import sys as s,os,zipfile as m;z=m.ZipFile(os.fdopen(s.stdout.fileno(),'wb'),'w');z.writestr(s.argv[1],s.stdin.read());z.close()" 'filename.sql' > output.zip

Python 3.5 添加了对写入不可搜索流的支持。

它不漂亮但有效。

于 2019-05-21T18:14:20.110 回答
-3

你可以试试:

mysql [params and query] | zip -q output.zip -@
于 2010-01-07T10:49:47.160 回答