Bash – (unix shell scripting) Unzip multiple zip files, rename unzipped file following zip file name

bashshellunixunzipzip

I have multiple zip files like this example:

759198298412.zip
----i love you.pdf
----forever and one.txt
----today and tomorrow.docs
48891721241592__5123.zip
----whatever it is.pdf
5717273_616.zip
----igotit.txt
----thank you very much.mp3    

I am trying to make a script to unzip the zip files, and rename the unzipped files to the zip file name. like this output:

759198298412.pdf
759198298412.txt
759198298412.docs

48891721241592__5123.pdf

5717273_616.txt
5717273_616mp3

I found this script below, but it doesn't work for me because my files have space and i have multiple files in a zip file.

for i in *.zip
do 
n=$(unzip -lqq $i | awk '{print $NF}')
e=${n#*.}
unzip $i && mv $n ${i%%_*}".$e"
done    

Please help! thank you

Best Solution

for i in *.zip; do
    mkdir "$i-dir"
    cd "$i-dir"
    unzip "../$i"
    for j in *; do
        mv "$j" "$i.${j##*.}"
    done
    cd ..
done

If dropping everything after the first underscore in the file name is important than the mv line should be:

mv "$j" "${i%%_*}.${j##*.}"

And to have that dropping work even when no underscore is present in the zip file name use:

i=${i%.zip}; mv "$j" "${i%%_*}.${j##*.}"

And to keep the files all in the top-level directory prefix ../ to the mv target filename.

Related Question