Extracting and renaming files from zip archives

I had a pile of zip files all containing different files, but also containing a file called preview.png that I wanted to extract and rename. Since the names of the zip are descriptive I wrote a bash script to loop over the files, extract the preview file and rename it. The interesting bit is stripping the .zip extension.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
#!/bin/bash

FILES=./*.zip
for F in $FILES
do
  echo "Processing $F file..."
  unzip "$F" preview.png
  FN=${F%.zip} # strip .zip
  mv preview.png "${FN##*/}.png"
done

For tar or gzipped tar the following will work in place of the ‘unzip’ line above:

1
2
tar -xf "$F" path/to/preview.png # extract from tar
tar -zxf "$F" path/to/preview.png # extract from tar.gz