(unix shell scripting) Unzip multiple zip files, rename the unzipped file after the zip file name

I have several 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 unpack zip files and rename the unpacked files to a zip file. 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 the 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

+3


source to share


3 answers


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 discarding everything after the first underscore in the filename is more important than the mv line, you would:

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

      



And to make this work dump even if there was no underscore in the zip file name, use:

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

      

And store the files in the top level directory prefix ../

in mv

target filename.

+5


source


A few small changes:

  • Quote variables to handle spaces in file names.
  • Use unzip -Z -1

    to list the files in the archive to avoid using awk (which only prints the trailing part of the names with spaces).
  • Since it unzip -Z -1

    splits records by line, we set IFS to '\ n' so records are split properly.
  • Replace the underscore with a dot to remove the .zip extension.

New script:

IFS=$'\n'
for i in *.zip
do
   for n in $(unzip -Z -1 "$i"); do 
       echo "$i - $n"
       e=${n#*.}
       unzip "$i" "$n" && mv "$n" ${i%%.*}".$e"
   done
done

      



Please note that this script assumes you only have one file extension in your zip code. If it doesn't, you will have to handle the duplicate files in some way.

Exit after startup:

48891721241592__5123.pdf  
48891721241592__5123.zip  
759198298412.docs  
759198298412.pdf  
759198298412.txt  
759198298412.zip

      

+1


source


for zip in *.zip; do
    zip_filename="${zip%%.*}"
    unzip "${zip}" -d "${zip_filename}-dir"

    for file in "${zip_filename}-dir"/*.*; do
        extension="${file##*.}"         
        new_name="${zip_filename}.${extension}"
        mv "${file}" "${new_name}"
    done

    rmdir "${zip_filename}-dir"
    # delete the zip file
    # rm "${zip}"
done

      

The script basically just unpacks the files into a new temp directory, then renames all the files in the new directory and pushes them out of the directory, and finally deletes the temp directory.

+1


source







All Articles