How can I use a single command to unzip every file in a directory, into a new unique directory with the same name as the file
Asked Answered
E

3

13

I have a directory full of zip files. Each called something like 'files1.zip'. My instinct is to use a bash for loop to unzip each file.

Trouble is, many of the files will unzip their contents straight into the parent directory, rather then unfolding everything into their own unique directory. So, I get file soup.

I'd like to ensure that 'files1.zip' pours all of it's files into a dir called 'files1', and so on.

As an added complication, some of the filenames have spaces.

How can I do this?

Thanks.

Epner answered 2/6, 2011 at 20:32 Comment(1)
P
20
for f in *.zip; do
  dir=${f%.zip}

  unzip -d "./$dir" "./$f"
done
Postorbital answered 2/6, 2011 at 20:50 Comment(0)
A
0

Simple one liner

$ for file in `ls *.zip`; do unzip $file -d `echo $file | cut -d . -f 1`; done
Antefix answered 9/11, 2016 at 21:1 Comment(1)
Your code doesn't work for zip file names having spaces or starting with a hyphen.Postorbital
A
-1

you can use -d to unzip to a different directory.

for file in `echo *.zip`; do
    [[ $file =~ ^(.*)\.zip$ ]]
    unzip -d ${BASH_REMATCH[1]} $file
done
Almund answered 2/6, 2011 at 20:46 Comment(1)
echo *.zip won't work for zip file names that contain spaces.Streetlight

© 2022 - 2024 — McMap. All rights reserved.