Renaming unzipped files with name of archive

I am attempting to rename files within a zipped archive with the beginning of the name of the zip file. For example unzip AAA_000.zip and rename file1.csv, file2.txt to AAA_file1.csv, AAA_file2.txt.

I am able to do this for a zip file with one file inside, but not for multiple files. This is the code I am using:

for i in *.zip
do 
n=$(unzip -lqq $i | awk '{print $NF}')
e=${n#*.}
unzip $i && mv $n ${i%%_*}".$e"
done

This is the error I get with multiple files inside the zipped archive:
mv: target `AAA_file1.csv\file2.txt' is not a directory

Thank you.

You could try something like this:

for i in *.zip
do
    cmd=$(unzip -lqq $i | awk -v z=${i%%_*} '{ print "mv " $NF " " z "_" $NF }')
    unzip $i && eval "$cmd"
done

Not if you have possibility of files in sub-folders you may need this:

for i in *.zip
do
        cmd=$(unzip -lqq $i | awk -v z=${i%%_*} '
        !/\/$/ && length {
           p=f=o=$NF
           gsub("[^/]*/", "",f)
           gsub(f"$","",p)
           print "mv "o " " p z "_" f
        }')
    unzip $i && eval "$cmd"
done

It's a little more complex because of support for files being in sub-directories.

1 Like

This did it! Thank you! My case was the first, but seeing both helps me understand how this works.