views:

241

answers:

2

I was sent a zip file containing 40 files with the same name. I wanted to extract each of these files to a seperate folder OR extract each file with a different name (file1, file2, etc).

Is there a way to do this automatically with standard linux tools? A check of man unzip revealed nothing that could help me. zipsplit also does not seem to allow an arbitrary splitting of zip files (I was trying to split the zip into 40 archives, each containing one file).

At the moment I am (r)enaming my files individually. This is not so much of a problem with a 40 file archive, but is obviously unscalable.

Anyone have a nice, simple way of doing this? More curious than anything else.

Thanks.

+5  A: 

Assuming that no such tool currently exists, then it should be quite easy to write one in python. Python has a zipfile module that should be sufficient.

Something like this (maybe, untested):

#!/usr/bin/env python

import os
import sys
import zipfile

count = 0

z = zipfile.ZipFile(sys.argv[1],"r")

for info in z.infolist():
    directory = str(count)
    os.makedirs(directory)
    z.extract(info,directory)
    count += 1

z.close()
Douglas Leeder
Wow, I didn't realize it'd be this simple.
Jefromi
Thanks for your answer, but I was looking for a technique that uses standard linux tools. However, this is most likely the most elegant solution.
pisswillis
python **is** pretty much a standard Linux tool.
Douglas Leeder
A: 

Hi Douglas Leeder, i've a compressed tar file with tha same problem: many files with the same name;

could you explain me how (if possible) phyton could "solve" the extraction?

many thanks!

Ah... phyton is a most elegant solution ;-)

I've modified the script for usiong it with the phyton tar module (tarfile):

#!/usr/bin/env python
import os
import sys
import tarfile

count = 0

t = tarfile.TarFile(sys.argv[1],"r")

for info in t.infolist():
    directory = str(count)
    os.makedirs(directory)
    t.extract(info,directory)
    count += 1

t.close()

but obtain the error:

./phyton-tar laura.tar.recovered_fixed.tar Traceback (most recent call last): File "./phyton-tar", line 11, in for info in t.infolist(): AttributeError: 'TarFile' object has no attribute 'infolist'

Davide Marchi
You should ask your question with the "Ask Question" button instead of answering one.
elblanco
You need to look at the methods the tarfile objects have and use those. In this case you can probably just iterate against the tar object itself.
Douglas Leeder