Linux: Unzip archive and rename contents to archive name followed by an incrementing number

25 Views Asked by At

I have several hundred .zip files sitting in a directory named /zip. All of the .zip files have a unique naming convention. For example: 123456_123456.zip

What I am trying to accomplish via command line for all of the .zip files:

  1. Unzip each archive. (Example 123456_123456.zip etc.)
  2. Rename each file that gets unzipped to the archive name followed by a incrementing number and with the files original extension. Example: Archive Contents = TEST123.pdf, TEST321.csv --> 123456_123456_1.pdf, 123456_123456_2.csv
  3. The incrementing number should reset to 0 as the script moves onto another archive.

Here is what I have so far.

for z in *.zip;
do 
num=0; 
sudo unzip -njB "$z"; 
sudo mv -b "$(unzip -Z1 $z)" "${z%%.*}_$((++num)).$(unzip -Z1 $z | awk -F'[.]' '{print $2}')";
done

This seems to work except for handling archives that have multiple files in them. When the script encounters an archive that contains multiple files it throws an error such as mv:cannot stat 'TEST123.pdf\nTEST321.csv':No such file or directory.

Any suggestions for getting the script to handle multiple files within an archive?

1

There are 1 best solutions below

0
thecarpy On

You need a second for loop for the extracted contents. (This is assuming no subdirs, assuming there are no files or dirs with tmp- prefix in that folder - other option, tmpdir - but not really portable)

for z in *.zip
do 
  num=0; 
  sudo unzip -njB "$z" -d tmp-$(basename ${z} zip)
  pushd "tmp-$(basename ${z} zip)"
  for a in *
  do 
    sudo mv -b "$(unzip -Z1 $a)" "${a%%.*}_$((++num)).$(unzip -Z1 $a | awk - F'[.]' '{print $2}')";
  done
  sudo rm -r "tmp-$(basename ${z} zip)"
  popd
done