I have various zip files that contain subfolders and no subfolders. I wish to extract all the zip to its folder. My current script does what I want if it contains subfolders. However, if there are no subfolder, it list them separately in same folder which will be confusing as I need to know what they are.
Before unzip folder structure:
JCB-1.zip
- JCB
- KDY231-8000018
-> file1.txt, file2.txt
- KGC30-0152537
-> file1.txt, file2.txt
- S330V-0034006
-> file1.txt, file2.txt
XZC605-0002319.zip
- file_1.txt ,file_2.txt, file_3.txt
ZNE10-7845839.zip
- ZNE10-7845839
-> file1.txt, file2.txt
After unzip folder structure:
- KDY231-8000018
- KGC30-0152537
- S330V-0034006
- file_1.txt
- file_2.txt
- file_3.txt
Current Script
#!/bin/bash
ZIPDIR=/mnt/www/log/_tmp
TMP=/tmp/zipfiles
cd $ZIPDIR
rm tmp/zipfiles 2>/dev/null
ls -l *.zip
if [ $? -eq 0 ]
then
echo ".zip file found"
ls -1 $ZIPDIR/*.zip > $TMP
for i in `cat $TMP`
do
unzip -o $i && rm $i
done
fi;
# Removing top level folder
mv $ZIPDIR/JCB/* . && rm -R JCB
if [ $? -eq 1 ]
then
echo "NOT found"
fi;
My thinking is that the zip that doesn't have subfolders, I will need to create them from fileName.zip and not from file_1.txt as the name doesn't make sense. Thus, the final result will be this structure after unzipping.
Final Expecting unzip folder structure:
- KDY231-8000018
- KGC30-0152537
- S330V-0034006
- XZC605-0002319
Updated: The code provide by @confetti works. Thanks. There is another zip file structure I forgot to mention and I have included above. Here is the final code with my edits. It may not be an efficient code, but it does seem to work for me.
#!/bin/bash
zipdir=/mnt/www/log/_tmp
cd $zipdir
for i in *.zip; do
folder=${i::-4}
mkdir -p $folder
unzip -o $i -d $folder && rm $i
subdirs=$(find $folder -type d | wc -l)
if [[ $subdirs -eq 2 ]]; then
mv ./$folder/* ./
rm -r $folder
else if [[ $subdirs -gt 1 ]]; then
mv ./$folder/*/* ./
rm -r $folder
fi
fi
done
1 Answer
#!/bin/bash
ZIPDIR=/mnt/www/log/_tmp
TMP=/tmp/zipfiles
cd "$ZIPDIR"
rm tmp/zipfiles 2>/dev/null
for i in ./*.zip; do
folder=${i::-4}
mkdir "$folder"
unzip -o "$i" -d "$folder" && rm "$i"
subdirs=$(find "$folder" -type d -printf ".\n" | wc -l)
if [[ $subdirs -gt 1 ]]; then
mv ./$folder/*/* ./
rm -r "$folder"
fi
done
Tested it with files similar to your shown structure and works perfectly for me.