在pipe道的命令行中创build文件时,如何指定压缩文件中的文件名?

我试图创build一个压缩文件的文件内容正在pipe道,例如

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

这会正确写入压缩文件,但是当您打开压缩文件时,其中的文件被称为“ – ”。 有什么办法指定什么文件中的pipe道数据应该在压缩?

从我可以收集你不能同时使用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结果unzip -p

 contents 

你可以这样做。

 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从标准输入中获取输入文件的列表。

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

 mkfifo output.txt ; mysql [params and query] > output.txt & zip output.zip -FI output.txt ; rm output.txt 

我无法管理PHP的答案 (在更大的MySQL转储内存不足),并且FIFO没有按照我想要的工作,所以我的解决方案是运行转储后使用zipnote(这是包含在Debian的zip包中)。

 mysql [params and query] | zip -q output.zip - echo -e "@ -\n@=newname.sql" | zipnote -w output.zip 

尝试

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