Bash to add unique prefix to extracted zip folder

In the bash below in each .zip there is a folder to be extracted Variants that I am trying to make unique by adding the prefix, before the _ from the .zip . The script does execute, but the prefix is not added to the extracted folder. Rather the Variants folder is added to each file within it. Thank you :).

bash

for z in /home/cmccabe/tmp/*.zip; do ## start loop
    unzip "$z";  ## unzip all .zip files
    mv "$(unzip -Z1 $z)" "${z%%_*}";  ## grab prefix before _ and add to the extraced .zip
rm "$z"  ## remove original .zip
done  ## end processing

/home/cmccabe/tmp

19-0000-LastName-FirstName_v1_c91a684a-0a9c-4632-9b60-91f0d337f51d.zip --- top level ---
     Variants   --- folder to be extracted ---
19-0002-L-F_v1_d870b844-b72e-49c4-89c4-471f90dd8724.zip   --- top level --
     Variants   --- folder to be extracted ---

desired output --- zip extracted ---

     19-0000-LastName-FirstName-Variants   --- extracted folder w/ prefix ---
     19-0002-L-F-Variants   --- extracted folder w/ prefix ---

example after executing currently --- one of 5 files, all extated in the same way ---

 inflating: Variants/19-0000-LastName-FirstName_v1/19-0000-LastName-FirstName_v1_Non-Filtered_2019-03-21_08:12:52-xxxx.tsv

Hello cmccabe,

I think that you are trying to do this in a single step, but actually you need to have more. Your attempt also has to be certain that you only have one file in each .zip but it's not clear if this is the case.

The problem is that unzip probably doesn't just give you the extracted filename(s) as output. You might well be better to make a temporary directory to extract the files to, then process all the files you find there. If the files are large, make the temporary directory in the same filesystem as the desired target. The default for mktemp is to make a directory with pattern /tmp/tmp.XXXXXXXX (might vary depending on OS) but you can set a template for the name to use so I have used it to set this all up in /data. Obviously change this to something meaningful for yourself.

There are a few variations on what you are asking for, but I've guessed at this one:-

target_dir=/data
for zipfile in /home/cmccabe/tmp/*.zip
do
   workdir=$(mktemp -d "${target_dir}"/tmp.XXXXX)                          # Creates the temporary directory and catches the name
   unzip -d "${workdir}" "${zipfile}"
   prefix="${zipfile%%_*}"                                                     # Grab the interesting bit for this input file
   for extracted_file in ${workdir}                                     
   do
      mv "${extracted_file}" "${target_dir}/${prefix}"                              # Move to desired location and rename in one step
   done
done

Does that do what you need or have I misunderstood your requirement?

I you are extracting multiple files, we might need to add a find into the loop to update the files safely.

Kind regards,
Robin