Search code examples
linuxfilearchiveunzip

unzip specific extension only


I have a a directory with zip archives containing .jpg, .png, .gif images. I want to unzip each archive taking the images only and putting them in a folder with the name of the archive.

So:

files/archive1.zip
files/archive2.zip
files/archive3.zip
files/archive4.zip

Open archive1.zip - take sunflower.jpg, rose_sun.gif. Make a folder files/archive1/ and add the images to that folder, so files/archive1/folder1.jpg, files/archive1/rose_sun.gif. Do this to each archive.

I really don't know how this can be done, all suggestions are welcome. I have over 600 archives and an automatic solution would be a lifesaver, preferably a linux solution.


Solution

  • Something along the lines of:

    #!/bin/bash
    cd ~/basedir/files
    for file in *.zip ; do
        newfile=$(echo "${file}" | sed -e 's/^files.//' -e 's/.zip$//')
        echo ":${newfile}:"
        mkdir tmp
        rm -rf "${newfile}"
        mkdir "${newfile}"
        cp "${newfile}.zip" tmp
        cd tmp
        unzip "${newfile}.zip"
        find . -name '*.jpg' -exec cp {} "../${newfile}" ';'
        find . -name '*.gif' -exec cp {} "../${newfile}" ';'
        cd ..
        rm -rf tmp
    done
    

    This is tested and will handle spaces in filenames (both the zip files and the extracted files). You may have collisions if the zip file has the same file name in different directories (you can't avoid this if you're going to flatten the directory structure).