[英]How do I unzip a “.zip” archive and redirect the output a specified file using Perl?
Lets say I have a zip file called myPartial.zip
and I want to unzip this myPartial.zip
archive and redirect the output to a file called output.txt
. 可以说我有一个名为myPartial.zip
的zip文件,我想解压缩myPartial.zip
档案并将输出重定向到一个名为output.txt
的文件。
To achieve that I could use the following shell script: 为此,我可以使用以下shell脚本:
unzip -Z1 myPartial.zip | grep -v "/$" >> my.log
My question is how do I do the same in Perl? 我的问题是我如何在Perl中做同样的事情?
There are a number of options for unzipping in Perl. 在Perl中有许多用于解压缩的选项。
First one is to just run the shell command in Perl. 第一个是只在Perl中运行shell命令。
system 'unzip -Z1 myPartial.zip | grep -v "/$" >> my.log';
Next is use one of the zip modules. 接下来是使用其中一个zip模块。 There are a few, including Archive::Zip , IO::Uncompress::Unzip and Archive::Zip::SimpleUnzip . 有一些,包括Archive :: Zip , IO :: Uncompress :: Unzip和Archive :: Zip :: SimpleUnzip 。
Whether you need to get into using one of the modules depends on the requirements of what you are doing. 是否需要使用其中一个模块取决于您所执行操作的要求。
Okay, so unzip -Z1 foo.zip
appears to list the filenames of the files in the zip archive, not extract the files. 好的,所以unzip -Z1 foo.zip
似乎会列出zip归档文件中文件的文件名 ,而不是提取文件。 That makes more sense for wanting everything in a single file. 将所有内容都放在一个文件中更有意义。 And you just want files, not directories. 您只需要文件,而不是目录。
So a perl one-liner: 因此,一个Perl单线:
perl -MArchive::Zip -E '$, = "\n"; say grep { m![^/]$! } Archive::Zip->new($ARGV[0])->memberNames' foo.zip >> my.log
But really, it's easier to just use unzip
/ zipinfo
like you already are. 但是实际上,像您已经使用zipinfo
一样,仅使用unzip
/ zipinfo
更容易。
You could try running the shell command directly using the system
method: 您可以尝试使用system
方法直接运行shell命令:
system("unzip -Z1 myPartial.zip | grep -v "/$" >> my.log");
If you'd like to terminate your script after execution is complete use the exec
method: 如果您想在执行完成后终止脚本,请使用exec
方法:
exec("unzip -Z1 myPartial.zip | grep -v "/$" >> my.log");
If you want to handle the program's output directly in PERL, simply use the backticks to execute the command and get it's output: 如果要直接在PERL中处理程序的输出,只需使用反引号执行命令并获取其输出:
$response = `unzip -Z1 myPartial.zip | grep -v "/$" >> my.log`;
You could then use print
to preview the output, like this: 然后,您可以使用print
预览输出,如下所示:
print $response;
Good luck. 祝好运。
Thanks guys. 多谢你们。 Using system command it worked. 使用系统命令可以正常工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.