Pmand
Pmand

Reputation: 7

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.

To achieve that I could use the following shell script:

unzip -Z1 myPartial.zip | grep -v "/$" >> my.log

My question is how do I do the same in Perl?

Upvotes: 1

Views: 1960

Answers (3)

Shawn
Shawn

Reputation: 52589

Okay, so unzip -Z1 foo.zip appears to list the filenames of the files in the zip archive, not extract the files. That makes more sense for wanting everything in a single file. And you just want files, not directories.

So a perl one-liner:

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.

Upvotes: 1

Malekai
Malekai

Reputation: 5031

You could try running the shell command directly using the system method:

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("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:

$response = `unzip -Z1 myPartial.zip | grep -v "/$" >> my.log`;

You could then use print to preview the output, like this:

print $response;

Good luck.

Upvotes: 0

pmqs
pmqs

Reputation: 3735

There are a number of options for unzipping in Perl.

First one is to just run the shell command in Perl.

system 'unzip -Z1 myPartial.zip | grep -v "/$" >> my.log';

Next is use one of the zip modules. There are a few, including Archive::Zip, IO::Uncompress::Unzip and Archive::Zip::SimpleUnzip.

Whether you need to get into using one of the modules depends on the requirements of what you are doing.

Upvotes: 1

Related Questions