Unix unzip: how to batch unzip zip files in a fold

2019-04-02 00:40发布

问题:

Say if I have a folder 'images' and inside it there are 0001.zip to 9999.zip, I want to unzip all of them and save them in subfolder which has their file name, for example, 0001.zip will be unzipped and saved to /0001, 0002.zip will be unzipped and saved to /0002, I tried to do

unzip '*.zip'

but that extracts all files in current folder.

回答1:

You could do something like this:

 for file in *.zip; do
       dir=$(basename "$file" .zip) # remove the .zip from the filename
       mkdir "$dir"
       cd "$dir" && unzip ../"$file" && rm ../"$file" # unzip and remove file if successful
       cd ..
  done

or, run it together on one line:

  for file in *.zip; do dir=$(basename "$file" .zip); mkdir "$dir"; cd "$dir"; unzip ../"$file" && rm ../"$file"; cd ..; done

If you need/want to keep the original .zip files, just remove the && rm ../"$file" bit.



回答2:

for zip in *.zip
do
    unzip "$zip" -d "${zip%.zip}"
done