Bash – Unzip Archive with Single File and Rename Output to Match Archive Name

bashcommand linerenamezip

The goal is to unzip many zip files and rename the resulting file to the original archive name.

Given a folder with many zip files, most of them containing a file called bla.txt, but of course there are some exceptions. All is known is that every file has a single file, which is a txt file.

./zips/
    a.zip - contains bla.txt
    b.zip - contains bla.txt
    c.zip - contains somethingelse.txt
    d.zip - contains bla.txt
    ...   - ...

output should be

./zips/
    a.txt
    b.txt
    c.txt
    d.txt
    ...  

Current best shot, which extracts everything but leaves me with a ton of folders:

for z in *.zip; do unzip $z -d $(echo 'dir_'$z); done

maybe something like

for z in *.zip; do unzip $z; mv 'content_name.txt' $z; done

But how is the content name obtained?

Best Answer

You could continue with the -d idea, and simply rename any extracted file to the desired "zip name minus the zip plus txt":

mkdir tmp
for f in *.zip; do unzip "$f" -d tmp && mv tmp/* "${f%.zip}.txt"; done
rmdir tmp

Alternatively, you could pipe the output from unzip into the appropriately-named file:

for f in *.zip; do unzip -p "$f" > "${f%.zip}.txt"; done